React-Redux 的使用
实现思路
使用Provider标签设置store来源,在页面组件中使用connect方法连接当前组件,同时将store中的state派发到当前的props,设置自定义的方法,也派发到当前的props上。
示例表达的意思是:
-
如果使用react-redux,就需要在入口文件index.js中使用Provider标签设置store来源
-
在页面组件中,使用connect连接当前页面和派发内容,定义两个变量 mapStateToProps 和 mapDispatchToProps。
-
页面需要的变量和方法,需要从props中解构出来。
-
创建action文件,定义reducer中的操作规则,返回新的state给store
-
react-redux 会自动订阅store的变化
-
页面内容改变
安装
npm install react-redux
// 或者
yarn add react-redux
使用Provider标签连接Store
说明:使用同一个Provider标签包裹的组件,可以共享注入的store
import ReactDOM from 'react-dom';
import { Provider } from "react-redux";
import './index.css';
import TodoList from './todo.list';
import store from "./store";
ReactDOM.render(
<Provider store={store}>
<TodoList />
</Provider>,
document.getElementById('root')
);
页面组件连接State和Dispatch
......
// 将store中的state派发到当前页面的props上
const mapStateToProps = (state) => ({
inputValue: state.inputValue,
list: state.list,
});
// 自定义函数,将其派发到当前页面组件的props上
const mapDispatchToProps = (dispatch) => ({
changeValue(e) {
const action = changeValueAction(e);
dispatch(action);
},
addItem() {
const action = addItemAction();
dispatch(action);
},
removeItem(index) {
const action = removeItemAction(index);
dispatch(action);
},
});
// connect 用于连接,将mapStateToProps和mapDispatchToProps两个方法,连接到TodoList上
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
创建Store
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(reducer);
export default store;
创建Reducer
import { ADD_ITEM, CHANGE_VALUE, REMOVE_ITEM } from "./action.types";
const defaultState = {
inputValue: "",
list: []
};
// eslint-disable-next-line import/no-anonymous-default-export
export default (state = defaultState, action) => {
if(action.type === CHANGE_VALUE) {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState
}
if(action.type === ADD_ITEM) {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue = "";
return newState
}
if(action.type === REMOVE_ITEM) {
const newState = JSON.parse(JSON.stringify(state));
newState.list.splice(action.index, 1);
return newState
}
return state
};
创建Action
export const CHANGE_VALUE = "change_value";
export const ADD_ITEM = "add_item";
export const REMOVE_ITEM = "remove_item";
// 变更
export const changeValueAction = (e) => ({
type: CHANGE_VALUE,
value: e.target.value
});
// 新增
export const addItemAction = () => ({
type: ADD_ITEM
});
// 移除
export const removeItemAction = (index) => ({
type: REMOVE_ITEM,
index
});