一、安装
yarn add redux
或者
npm install --save-dev redux
二、创建相应目录
在src文件夹下创建store文件夹,在src文件夹下创建相应文件
1.创建store的入口文件idex.js
Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。
当前时刻的 State,可以通过store.getState()拿到。
import { createStore } from 'redux';
import reducer from './reducers/index'
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() --开发者redux -devTools配置
);
export default store;
Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然
要看到状态值的变化,--要到谷歌插件市场下载redux --devloos插件
2.Action
State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。
Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置
创建一个actionTypes.js的属性文件的js供使用
例如:
export const CHANGINPUT = 'CHANGINPUT'
export const ADDBBIMN = 'Add_bbimn'
export const DELEMTITEM = 'DelemtItem'
export const UPDATEINFO = 'UPdateinfo'
3.Action Creator
View 要发送多少种消息,就会有多少种 Action。如果都手写,会很麻烦。可以引入刚才创建的 Action,
在 /src/store/action/
目录下创建actionCreators.js
import { CHANGINPUT, ADDBBIMN, DELEMTITEM, UPDATEINFO } from "./actionTypes";
export const changInput = (value) => ({
type: CHANGINPUT,
value: value
})
export const addbindCheng = () => ({
type: ADDBBIMN,
})
export const deleteItemCheng = (index) => ({
type: DELEMTITEM,
value:index
})
export const updateinfo = (value) => ({
type: UPDATEINFO,
value: value,
});
4.Reducer更新数据状态
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
在/src/store/reducers
创建index.js文件
import { CHANGINPUT, ADDBBIMN, DELEMTITEM ,UPDATEINFO } from "../actions/actionTypes";--引入action属性文件
const defaultState = {
userInfo: {
username: "李四",
age: 28,
sex: "男",
},
};
export default (state = defaultState, action) => {
if (action.type === CHANGINPUT) {
// Reducer 里只能接受 state 不能改变state
let newStade = JSON.parse(JSON.stringify(state));
newStade.inputValue = action.value;
return newStade;
}
if (action.type === ADDBBIMN) {
let newStade = JSON.parse(JSON.stringify(state));
newStade.list.push(newStade.inputValue);
return newStade;
}
if (action.type === DELEMTITEM) {
let newStade = JSON.parse(JSON.stringify(state));
newStade.list.splice(action.value, 1);
return newStade;
}
if (action.type === UPDATEINFO){
let newStade = JSON.parse(JSON.stringify(state));
newStade.userInfo.username = action.value;
return newStade;
}
return state;
};
5.如何使用
在页面中引入相应的文件
import store from "../../../store";
import { updateinfo } from "../../../store/actions/actionCreators"; --我这里只用到了更新用户信息的
如我在用户列表里更新用户信息