问题描述
几个小时后我不得不寻求帮助,我的useEffect并不总是在reduxs调度操作上起作用。
const ScreenA = { currentItem,updatedItem } => {
useEffect(() => {
if (currentItem.id === updatedItem.id) { // Do stuff }
},[updatedItem]) // XX Is not changing
... // do stuf
const mapStatetoProps = (state) => {
console.log("AAABB ScreenA.mapStatetoProps updatedItem: ",state.updatedItem) // XX I receive new updated id!! but it doesn't change the prop.updatedItem for ScreenA and useEffect is not calling.
return {
updatedItem: state.updatedItem,}
}
export default connect(mapStatetoProps)(FeedScreen)
}
我的减速机 更新
const initialState = {
updatedItem: undefined,}
export default (state = initialState,action) => {
switch (action.type) {
case ITEM_CHANGED:
console.log("AAABB reducer.addChangedItem.ITEM_CHANGED: " + action.t) // Is printing after every dispatch call
return {
...state,updatedItem: action.updatedItem,}
// I tried also with
return {
updatedItem: action.updatedItem,}
default:
return state
}
}
奇怪的是,如果我将更改操作从ScreenB调度到ScreenA,而不是在ScreenC和ScreenA之间调度,它会起作用。 (这与我分发动作的方式相同。
解决方法
也分发您的更新项目
由于更新的项目是一个对象,可能会导致突变。似乎不太可能,但这是不使用平面数据时面临的问题。通常,在redux中,您的操作中还会有一个type
和一个payload
(未更新的项目)。
return {
...state,updatedItem: {...action.updatedItem},}
如果这不起作用,则可能是您useEffect中的某个内容已损坏,您需要在其中登录并显示结果。