首页 > 代码库 > react回顾

react回顾

读书就像盖房子,根基要正,刚开始要选一些文风简明的。。。react 小书 就不错。

创建组件(extends 或是 stateless)

父子组件之间的通信(super)

事件监听(event对象和this)

渲染列表(map)

状态提升(state)

挂载阶段声明周期

更新阶段生命周期(setState)

容器类组件(this.props.children)

Proptypys验证

defaultProps

高阶组件(返回新的组件类)

getChildContext(childContextTypes):慎重

 

redux基本原理

createStore基本实现

function createStore (reducer) {
  let state = null
  const listeners = []
  const subscribe = (listener) => listeners.push(listener)
  const getState = () => state
  const dispatch = (action) => {
    state = reducer(state, action)
    listeners.forEach((listener) => listener())
  }
  dispatch({}) // 初始化 state
  return { getState, dispatch, subscribe }
}

reducer基本实现

function themeReducer (state, action) {
  if (!state) return {
    themeName: ‘Red Theme‘,
    themeColor: ‘red‘
  }
  switch (action.type) {
    case ‘UPATE_THEME_NAME‘:
      return { ...state, themeName: action.themeName }
    case ‘UPATE_THEME_COLOR‘:
      return { ...state, themeColor: action.themeColor }
    default:
      return state
  }
}

redux基本流程

// 定一个 reducer
function reducer (state, action) {
  /* 初始化 state 和 switch case */
}

// 生成 store
const store = createStore(reducer)

// 监听数据变化重新渲染页面
store.subscribe(() => renderApp(store.getState()))

// 首次渲染页面
renderApp(store.getState()) 

// 后面可以随意 dispatch 了,页面自动更新
store.dispatch(...)

 

react-redux原理

connect(mapStateToProps,mapDispatchToProps)(WrappedComponent )基本实现

export const connect = (mapStateToProps, mapDispatchToProps) => (WrappedComponent) => {
  class Connect extends Component {
    static contextTypes = {
      store: PropTypes.object
    }

    constructor () {
      super()
      this.state = {
        allProps: {}
      }
    }

    componentWillMount () {
      const { store } = this.context
      this._updateProps()
      store.subscribe(() => this._updateProps())
    }

    _updateProps () {
      const { store } = this.context
      let stateProps = mapStateToProps
        ? mapStateToProps(store.getState(), this.props)
        : {} // 防止 mapStateToProps 没有传入
      let dispatchProps = mapDispatchToProps
        ? mapDispatchToProps(store.dispatch, this.props)
        : {} // 防止 mapDispatchToProps 没有传入
      this.setState({
        allProps: {
          ...stateProps,
          ...dispatchProps,
          ...this.props
        }
      })
    }

    render () {
      return <WrappedComponent {...this.state.allProps} />
    }
  }
  return Connect
}

Provider基本实现

export class Provider extends Component {
  static propTypes = {
    store: PropTypes.object,
    children: PropTypes.any
  }

  static childContextTypes = {
    store: PropTypes.object
  }

  getChildContext () {
    return {
      store: this.props.store
    }
  }

  render () {
    return (
      <div>{this.props.children}</div>
    )
  }
}

组件划分原则(components和containers)

什么时候使用connect,什么时候使用props???

评论组件模块思路(编写思路,从UI组件需求出发):

  • 评论框组件UI界面(component):
  1. 设置this.state{username:"",context:""}
  2. 设置input[username和textarea[context]的value监听器,this.setState
  3. 点击提交时触发this.props.onSubmit并将当前state作为参数,之后重置state
  • 评论框组件容器(container):
  1. 设置评论框组件UI界面的props接口
     <CommentInput onSubmit={this.handleSubmitComment.bind(this)} />

     

  2. 编写handleSubmitComment的逻辑。逻辑函数即connect(mapStateToProps,mapDispatchToProps)(WrappedComponent )中的mapDispatchToProps的返回值
    const mapDispatchToProps = (dispatch) => {
        return {
            onSubmit: (comment) => {
                dispatch(addComment(comment))
            }
        }
    };

     

  3. 通过connect包装
  • 评论列表UI组件(component):
  1. 暴露this.props.comments接口并map渲染数据
  2. 点击删除时触发this.props.onDeleteComment并将index作为参数
  • 评论列表组件容器(container):
  1. 设置评论列表UI组件的props接口
    <CommentList
                    comments={this.props.comments}
                    onDeleteComment={this.handleDeleteComment.bind(this)}
                />

     

  2. 编写handleDeleteComment的逻辑。逻辑函数即connect(mapStateToProps,mapDispatchToProps)(WrappedComponent)中的mapDispatchToProps的返回值
    const mapDispatchToProps = (dispatch) => {
        return {
            // 删除评论
            onDeleteComment: (commentIndex) => {
                dispatch(deleteComment(commentIndex))
            }
        }
    };

    省略了初始化comment。

  3. 设置conmments。即connect(mapStateToProps,mapDispatchToProps)(WrappedComponent)中的mapStateToProps的返回值(store.getState())
    const mapStateToProps = (state) => {
        return {
            comments: state.comments
        }
    };

     

  • 编写增删的reducer。即实现修改state。这里将新建action生成器,返回值即dispatch的参数。
    export const addComment = (comment) => {
        return {type: ADD_COMMENT, comment}
    };
    
    export const deleteComment = (commentIndex) => {
        return {type: DELETE_COMMENT, commentIndex}
    };

     

  • 创建store,传入Provider包裹组件
    const store = createStore(commentsReducer);
    
    ReactDOM.render(
        <Provider store={store}>
            <CommentApp />
        </Provider>,
        document.getElementById(‘root‘)
    );

     

react基本回顾就这些了

 

react回顾