首先下载redux插件
yarn add redux
- 项目目录src下创建store文件夹,然后再创建两个文件分别index.js reducer.js
- 在index.js中引入redux 并使用createStore
- reducer放置初始数据,以及接收到的type后对应的操作
index.js
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(reducer);
export default store;
reducer.js
const defaultState = {
inputValue: "毛不易",
list: ["像我这样的人", "一程山路", "消愁", "无问"],
};
// reducer可以接收state,但绝不能修改state
export default (state = defaultState, action) => {
if (action.type === CHANGE_INPUT_VALUE) {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
}
- 如何获取store里面定义的值:this.state = store.getState();
import store from "./store";
export default class Todo extends Component {
constructor(props) {
super(props);
this.state = store.getState();//与store通信,获取store中的数据
}
}
- 如何与store交互,修改值?
向store派发action
import store from "./store";
inputChange(e) {
const action ={
type: "change_input_value",
value:"e.target.value"
}
store.dispatch(action);
}
reducer中根据type接收 做相应处理
const defaultState = {
inputValue: "毛不易",
list: ["像我这样的人", "一程山路", "消愁", "无问"],
};
// reducer可以接收state,但绝不能修改state
export default (state = defaultState, action) => {
if (action.type === CHANGE_INPUT_VALUE) {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
}
怎么在组件中再次获取实时的数据?(订阅)store.subscribe(this.handleStoreChange);
import store from "./store";
export default class Todo extends Component {
constructor(props) {
super(props);
store.subscribe(this.handleStoreChange);
}
handleStoreChange() {
this.setState(store.getState());
}
}
至此:react与redux的交互结束
完善react与redux交互,
主要解决的问题:当type类型设置为常量的时候,更加容易定位到报错,所以新增actionType.js用于放置常量
export const CHANGE_INPUT_VALUE = "change_input_value";
export const ADD_TODO_ITEM = "add_todo_item";
export const DELETE_TODO_ITEM = "delete_todo_item";
新增actionCreators.js文件,用于统一放置action,以函数的形式导出,有利于前端自动化测试,有利于统一维护
import {
CHANGE_INPUT_VALUE,
ADD_TODO_ITEM,
DELETE_TODO_ITEM,
} from "./actionType";
export const getInputChangeAction = (value) => ({
type: CHANGE_INPUT_VALUE,
value,
});
export const getAddItemAction = () => ({
type: ADD_TODO_ITEM,
});
export const getDeleteItemAction = (index) => ({
type: DELETE_TODO_ITEM,
index,
});
在组件中如何调用?
import store from "./store";
import {
getInputChangeAction,
getAddItemAction,
getDeleteItemAction,
} from "./store/actionCreators";
inputChange(e) {
const action = getInputChangeAction(e.target.value);
store.dispatch(action);
}
submitHandle() {
const action = getAddItemAction();
store.dispatch(action);
}
deleteItem(index) {
const action = getDeleteItemAction(index);
store.dispatch(action);
}
惟愿山河无恙,国泰民安,幸哉~