乐趣区

react redux学习

1、安装 redux yarn add redux
2、创建 store

列表项目创建 store 文件夹
文件夹下创建 index.js
index.js

import {createStore} from ‘redux’;
const store = createStore();
export default store;
3、创建 reducer.js
const defaultState = {
inputValue:””
}
export default (state = defaultState,action) => {return state}
5、store 中如何获取 reducer 的数据,及改变
//index.js 做如下修改
import {createStore} from ‘redux’;
import reducer from ‘./reducer’
const store = createStore(reducer);
export default store;
6、组件中如何获取 store 数据

组件中引入 store 文件下的 index.js
在 constructor 中 this.state = store.getState();

7、如何改变 store 的数据

创建 action const action = {type:’input_action’,val:val};
store.dispatch(action) -> store ->reducer 改变 store 数据 返回一个新的 state 数据

8、如何监听 store 的数据改变,刷新 dom

组件中的 constructor 使用 store.subscribe(this.listener.bind(this));
listener () { this.setState(store.getState())};

退出移动版