Redux 入门

  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())
    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容