皖林 2020-05-11
应用中所有的 state 都以一个对象树的形式储存在一个单一的 store 中,store接收reducer作为参数,store通过API(如dispatch)来接受action来调用reduce;
惟一改变 state 的办法是触发 action (描述如何处理state的对象);
为了实现根据 action 的信息来改变 state 树,需要编写 reducers函数,reducer定义如何操作对应的state;

import React from "react";
import ReactDOM from "react-dom";
import Redux, {createStore} from "redux";
// create actions
const ADD_ACTION = "ADD";
const REDUCE_ACTION = "REDUCE";
const add = num => {
return {
type: ADD_ACTION,
num
};
};
const reduce = num => {
return {
type: REDUCE_ACTION,
num
};
};
// initialize a state
const initialState = {
count: 0
};
// create a reducer
const reducer = (state = initialState, action) => {
switch (action.type) {
case "ADD":
return Object.assign({}, state, {
count: state.count + action.num
});
case "REDUCE":
return Object.assign({}, state, {
count: state.count - action.num
});
default:
return state;
}
};
function getCurrentState() {
return reduxStore.getState(); // 获取当前的state对象
}
function addState() {
reduxStore.dispatch(add(1));
console.log(getCurrentState()); // 每点击一次count会加1,如{count: 1}
}
function reduceState() {
reduxStore.dispatch(reduce(1));
console.log(getCurrentState()); // 每点击一次count会减1,如{count: 0}
}
const reduxStore = createStore(reducer);
console.log(reduxStore.getState());
class App extends React.Component {
constructor(props) {
super(props);
//初始化 state
this.state = getCurrentState();
}
render() {
return (
<div>
<h1>A Redux Example, open console to check results.</h1>
<button onClick={addState}>add</button>
<button onClick={reduceState}>reduce</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>, rootElement);connect 方法具体的作用是将store和组件联系在一起
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options]);
[mapStateToProps(state, [ownProps]): stateProps] (Function)改方法允许我们将store中的数据作为props绑定到组件中,只要store发生了变化就会调用mapStateToProps方法,mapStateToProps返回的结果必须是一个纯对象,这个对象会与组件的 props 合并,例子:
const mapStateToProps = (state) => {
return ({
count: state.counter.count
});
}[mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function)允许我们将 action 作为 props 绑定到组件中。