内容简介:在react中组件与组件之间的通信很麻烦,于是借用redux进行第三方的通信,通过把数据存储在store里,实现各个组件间快速通信
使用redux 目的
在react中组件与组件之间的通信很麻烦,于是借用redux进行第三方的通信,通过把数据存储在store里,实现各个组件间快速通信
redux 基础
1. 核心
- state:普通对象
- action:JS 普通对象,用来描述发生了什么,store 数据的唯一来源
- reducer:把 action 和 state 串起来。接收 state 和 action 作为参数,并返回新的 state 的函数。
2. 三大原则
- 单一数据源:只存在唯一一个store
- state只读:唯一改变 state 的方法就是触发 action
- 使用纯函数进行修改:reducer
3. 主要组件
-
action
通过dispatch传递数据到store
-
reducer
描述如何响应action更新state
-
store
维持应用的 state;
提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
通过 subscribe(listener) 注册监听器;
通过 subscribe(listener) 返回的函数注销监听器。
安装redux
npm install redux --S
准备工作
1. 创建 store
// store/index.js
import {createStore} from 'redux';
import reducer from './reducer';
const store = createStore(
reducer,
);
export default store;
2. 创建 reducer
// store/reducer.js
// 初始 state
const initState={
inputValue:'',
list:[]
};
// reducer可以接收state,但是绝不能修改state,返回的是新的state
export default (state = initState,action)=>{
return state;
}
流程
1. store 的 dispatch(action) 传递 action 给 store,store 会自动转发给 reducer
InputChange = (e) => {
// 告诉store, 输入的类型和输入框中的值
const action = {
// type 属性 必须有
type:'change_input_value',
value: e.target.value,
};
// 把 action 传给 store
store.dispatch(action);
// store 自动传给 reducer
};
2. reducer 接收信息,并返回给 store 一个 newState
export default (state = initState,action)=>{
if (action.type==='change_input_value'){
const newState = JSON.parse(JSON.stringify(state)); //简单的深拷贝
newState.inputValue = action.value;
return newState;
}
}
3. TodoList 监听 state 的变化
constructor(props){
super(props);
this.state = store.getState();
//监听store里面的变化,只要store里面的数据发生改变,则立即执行subscribe函数里的函数
store.subscribe(this.handleStoreChange)
}
StoreChange=()=>{
this.setState(store.getState());
// 感知store发生变化之后,从store里获取最新的数据,然后进行设置
};
以上所述就是小编给大家介绍的《react + redux 基本用法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Is Parallel Programming Hard, And, If So, What Can You Do About
Paul E. McKenney
The purpose of this book is to help you understand how to program shared-memory parallel machines without risking your sanity.1 By describing the algorithms and designs that have worked well in the pa......一起来看看 《Is Parallel Programming Hard, And, If So, What Can You Do About 》 这本书的介绍吧!