我在我的React Native移动应用程序中有一个模式组件。它从Redux状态接收对象数组。我可以使用useDispatch
钩子调度动作来删除数组中的特定项目。但是,在发送删除操作后,组件状态不会自动更新,因此我每次必须重新打开模式才能查看更新后的列表。当使用dispatch
更改Redux状态时,如何将模态设置为自动重新渲染?非常有用的建议。
SelectedItems.js
const SelectedItems = () => {
const vegetables = useSelector(state => state.new_order.vegetables)
return (
<Modal visible={isVisible}>
{vegetables.map( (v,index) =>
<VegeItem
key={index}
index={index}
name={v.name}
qty={v.qty}
metric={v.metric}
removeItem={(index) => {
dispatch({
type: 'DELETE_VEGE',
id: index
})
}}
/>)}
</View>
</Modal>
)
}
newOrderReducer.js
const newOrderReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'ADD_VEGE':
let updatedList = [...state.vegetables,action.vege]
return {
...state,
vegetables: updatedList
}
case 'DELETE_VEGE':
let newVegeList = state.vegetables
newVegeList.splice(action.id,1)
return {
...state,
vegetables: newVegeList
}
default:
return state
}
};
[let newVegeList = state.vegetables
这样做时,newVegeList
只是状态的指针,而不是状态的浅表副本,您仍然无法对其进行突变,因为您无法对化简器的return
部分进行状态突变。
所以您可以像let newVegeList = [...state.vegetables]
一样直接使用,也可以直接在返回处使用
return {
...state,
vegetables: state.vegetables.splice(action.id,1)
}