redux的使用流程

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36784628/article/details/95232859

1 、安装

npm install --save redux

2、在src目录下新建index.js和reducer.js

index.js中

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

reducer.js中定义数据

const defaultState = {
    inputValue : 'Write Something',
    list:[
        '早上4点起床,锻炼身体',
        '中午下班游泳一小时'
    ]
}
export default (state = defaultState,action)=>{
    return state
}

3、组件中使用

import store from './store/index' //引入

//构造函数中获取数据
 constructor(props){
        super(props)
        this.state=store.getState();
 }


//js中使用

{{this.state.inputValue}}

3、store值的修改(input框触发方法)

onChange={this.changeInputValue}

方法内获取到输入的值,定义action,并通过dispatch()方法传递给store

changeInputValue(e){
    const action ={
        type:'changeInput',//这个值自定义
        value:e.target.value
    }
    store.dispatch(action)
}

在reducer.js文件中,更改值

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
}

回到组件,在构造函数中订阅

constructor(props){
    super(props)
    this.storeChange = this.storeChange.bind(this)  //转变this指向
    store.subscribe(this.storeChange) //订阅Redux的状态
}

在storeChange方法中重新获取store的数据

storeChange(){
     this.setState(store.getState())
 }

猜你喜欢

转载自blog.csdn.net/qq_36784628/article/details/95232859