假设我有一个POST请求,它将对象中属性的状态更新为true / false。
在我的reducer中,我在发布请求成功后将其作为一个动作发送。
case "ADD_CHANGE_TO_TRUE_RESOLVE":
if (action.res.errorCode == 0) {
console.log("NO ERROR!");
// DO SOMETHING
}
目前,状态可以在后端更改,但除非我刷新页面,否则“真实”状态不会反映在DOM中(我在componentDidMount()上执行GET请求以在页面刷新时获取最新数据) 。
我的问题是如何在发布请求后立即更改商店中的状态(通过单击按钮触发POST请求)?
我这样做吗?
case "ADD_CHANGE_TO_TRUE_RESOLVE":
if (action.res.errorCode == 0) {
console.log("NO ERROR!");
const objChanged = newState.list.find(function (obj) { return obj.id === action.res.data.id; });
objChanged.is_favorite = true;
考虑到我将此作为我在商店中的州:
const currentState = [
{
list: []
}
];
我对redux /做出反应非常新,所以我不确定我是否正确地做到了。
你不应该直接改变状态值。此外,在成功的API请求之后调度操作时,您只需将id作为请求的有效负载传递
dispatch({
type: 'ADD_CHANGE_TO_TRUE_RESOLVE',
id: res.data.id
})
现在在商店里,你可以像处理一样
case "ADD_CHANGE_TO_TRUE_RESOLVE": {
const objIndex = state.list.findIndex(function (obj) { return obj.id === action.id; });
if(objIndex > -1) {
// return the updated state if the id was found
return {
...state,
list: [
...state.list.slice(0, index),
{...state.list[objIndex], is_favorite: true},
...state.list.slice(index + 1)
]
}
}
// otherwise return the state as it is
return state
}
你可以将州存储为
this.setState({[stateName]:value});
如果你使用ajax或axios,你必须首先绑定函数
this.apicallfunction = this.apicallfunction.bind(this);
通过传递id动作,您可以使用'react-addons-update'更新它:
import update from 'react-addons-update'
case "ADD_CHANGE_TO_TRUE_RESOLVE": {
if(action.id > -1){
return update(state, {
list: {
[action.id]: {
is_favorite: { $set: true }
}
}
})
}
else{
return state
}
}