美文网首页
Redux 入门

Redux 入门

作者: wkylin | 来源:发表于2019-08-17 23:08 被阅读0次
    1. store

    import { createStore } from 'redux' // 引入createStore方法
    import reducer from './reducer'
    const store = createStore(reducer) // 创建数据存储仓库
    export default store //暴露出去

    1. reducer

    const defaultState = {} //默认数据
    export default (state = defaultState, action)=>{ //就是一个方法函数

    1. // console.log(state, action)
      return state
      }

    2. component
      import store from './store'
      constructor(props){
      super(props)
      //关键代码-----------start
      this.state=store.getState();
      //关键代码-----------end
      console.log(this.state)
      }

    3. onClick 执行的方法
      changeInputValue(e){
      const action ={
      type:'changeInput',
      value:e.target.value
      }
      store.dispatch(action)
      }

    4. reducer 改变state
      export default (state = defaultState, action)=>{
      if(action.type === 'changeInput'){
      let newState = JSON.parse( JSON.stringify (state)) //深度拷贝state
      newState.inputValue = action.value
      return newState
      }
      return state
      }

    5. 更新 component
      constructor(props){
      super(props)
      this.state=store.getState();
      this.changeInputValue= this.changeInputValue.bind(this)
      //----------关键代码-----------start
      this.storeChange = this.storeChange.bind(this) //转变this指向
      store.subscribe(this.storeChange) //订阅Redux的状态
      //----------关键代码-----------end
      }
      storeChange(){
      this.setState(store.getState())
      }

    相关文章

      网友评论

          本文标题:Redux 入门

          本文链接:https://www.haomeiwen.com/subject/fxdlsctx.html