react-redux是一种react官方推出的redux管理工具 他的好处就是 我们不需要再用store.subscribe去监听数据变化再去重新渲染项目了 项目自己会检查状态修改并重新渲染界面
但很多人都会遇到用一个对象 明明数据改了 但界面就是没有重新渲染
这个问题要修改 counter
我的代码是这样的
let stateMap = {
name: "小猫猫",
money: 2800
}
const counter = ( state = stateMap,action ) => {
switch(action.type) {
case"PriceRise":
state.money = (state.money + action.value);
return state
case"DevaLuation":
state.money = (state.money - action.value);
return state
default:
return state;
}
}
export default counter
确实问题就是 你的对象如果没有深拷贝 react项目检查不到你的数据改变了
我们将代码改成
let stateMap = {
name: "小猫猫",
money: 2800
}
const counter = ( state = stateMap,action ) => {
switch(action.type) {
case"PriceRise":
state = JSON.parse(JSON.stringify(state));
state.money = (state.money + action.value);
return state
case"DevaLuation":
state = JSON.parse(JSON.stringify(state));
state.money = (state.money - action.value);
return state
default:
return state;
}
}
export default counter
就可以了
简单说 就是每次要改对象数据前 先将对象深拷贝一次 react项目就能检查到 并重新渲染界面了