1.定义Action的类别
export const ADD = 0;
export const SUB = 1;
2.定义Action的生成器
import { ADD, SUB } from "./action-type";
export function addCreator(num = 1) {
return {
type: ADD,
data: num
};
}
export function subCreator(num = 1) {
return {
type: SUB,
data: num
};
}
//异步Action生成器
export function asyncAddCreator(num = 1) {
return function(dispatch) {
setTimeout(function() {
dispatch({
type: ADD,
data: num
});
}, 1500);
};
}
3.定义Action处理函数 Reducer
import { ADD, SUB } from "./action-type";
export function CountReducer(state = 0, action) {
console.log("state:", state, "\naction:", action);
switch (action.type) {
case ADD:
return state + action.data;
case SUB:
return state - action.data;
default:
return state;
}
}
4.根据Reducer创建store
import { createStore, applyMiddleware } from "redux";
import { CountReducer } from "./reducers";
// 在 Redux 中,中间件是纯粹的函数,
// 有明确的使用方法并且严格的遵循以下格式:
function middleWare({ dispatch, getState }) {
return function(next) {
return function(action) {
// 中间件业务相关代码
return typeof action === "function"
? action(dispatch, getState)
: next(action);
};
};
}
// 1) 第一层向其余两层提供分发函数和 getState 函数(因为你的中间件或 action creator 可能需要从 state 中读取数据)
// 2) 第二层提供 next 函数,它允许你显式的将处理过的输入传递给下一个中间件或 Redux(这样 Redux 才能调用所有 reducer)。
// 3) 第三层提供从上一个中间件或从 dispatch 传递来的 action,这个 action 可以调用下一个中间件(让 action 继续流动) 或者以想要的方式处理 action。
const store = createStore(CountReducer, applyMiddleware(middleWare));
export default store;
5.业务逻辑App的实现
import React from "react";
import {
addCreator,
subCreator,
asyncAddCreator
} from "./redux/action-creator";
import { connect } from "react-redux";
class App extends React.Component {
constructor(x) {
super(x);
this.handleAdd = this.handleAdd.bind(this);
this.handleSub = this.handleSub.bind(this);
this.handleAsyncAdd = this.handleAsyncAdd.bind(this);
}
handleAdd() {
this.props.increase(1);
}
handleSub() {
this.props.decrease(1);
}
handleAsyncAdd() {
this.props.asyncIncrease(5);
}
render() {
return (
<div>
<div>Number:{this.props.count}</div>
<button onClick={this.handleAdd}>ADD</button>
<button onClick={this.handleSub}>SUB</button>
<button onClick={this.handleAsyncAdd}>AsyncADD</button>
</div>
);
}
}
//将store里的state映射到组件的属性
function mapStateToProps(state) {
return {
count: state //count就成为组件的一个属性
};
}
//将store的dispatch映射到组件的属性
function mapDispatchToProps(dispatch) {
return {
increase: num => {
dispatch(addCreator(num));
},
decrease: num => {
dispatch(subCreator(num));
},
asyncIncrease: num => {
dispatch(asyncAddCreator(num));
}
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
6.将store引入React中
import React from "react";
import { render } from "react-dom";
import App from "./App.jsx";
import { Provider } from "react-redux";
import store from "./redux/store";
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
附