引入Redux就是为了方便管理状态,那么在React代码中如何使用了。
换句话说就是如何使用storea里面维护的state,然后在react中如何产生action,用于更新state。
我们需要用的一个connect函数。
具体看代码
import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers, bindActionCreators } from "redux";
import { Provider, connect } from "react-redux";
import "./styles.css";
const initState = { count: 0 }; //默认初始状态
const counter = (state = initState, action) => {
switch (action.type) {
case "add": // + 1
return { count: state.count + 1 };
case "sub": // - 1
return { count: state.count - 1 };
case "addAny": // + action.num
return { count: state.count + action.num };
default:
break;
}
return state;
};
const store = createStore(counter); //生成store
function addOne() {
//action产生函数 返回一个add action
return {
type: "add"
};
}
function subOne() {
// 返回一个sub action
return {
type: "sub"
};
}
function subAnyCount(cnt) {
// 返回一个add cnt action
return {
type: "addAny",
num: cnt
};
}
class Counter extends React.Component {
constructor(props) {
super(props);
}
render() {
const { count, addOne, subOne } = this.props;
//接受到的三个参数,
return (
<div>
<button onClick={subOne}>-</button>
<span> {count}</span>
<button onClick={addOne}>+</button>
</div>
);
}
}
//定义了一个函数,用于返回我需要的state.count
function mapStatesToProps(state) {
return {
count: state.count
};
}
//因为action都需要dispatch,
function mapdispatchToProps(dispatch) {
return bindActionCreators({ addOne, subOne }, dispatch);
}
//这是关键,Counter就会接受到三个参数
const ConnectCounter = connect(
mapStatesToProps,
mapdispatchToProps
)(Counter);
const html = (
<Provider store={store}>
<ConnectCounter />
</Provider>
);
ReactDOM.render(html, document.getElementById("root"));
效果如图,点击+,则+1,点击-,则-1