reactjs - 使用钩子更改 Redux 状态时,React Native 模式不会更新
问题描述
我的 React Native 移动应用程序中有一个模态组件。它从 Redux 状态接收一组对象。我可以使用useDispatch
钩子调度操作来删除数组中的特定项目。但是,发送删除动作后,组件状态并没有自动更新,所以我每次都要重新打开modal才能看到更新的列表。
当使用更改 redux 状态时,如何将模式设置为自动重新渲染dispatch
?
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
reducer 部分之外的状态。
所以你可以做like let newVegeList = [...state.vegetables]
,或者直接在return
return {
...state,
vegetables: state.vegetables.filter((veg, i) => i != action.id)
}
您还可以发送蔬菜名称或其他任何内容并在以下位置修改检查器filter
推荐阅读
- android - android中的ClassCastException,同时实现手动创建的新支持类
- vue.js - vue.js:nextTick如何保证数据变化后dom渲染完成?
- c# - Unity raycast 在编辑器和构建之间具有不同的行为
- bintray - nebula.release 插件尝试将根项目推送到 bintray
- liquibase - Liquibase 使用 maven 生成具有多个模式的 generateChangeLog
- django - 旧数据库中关联表的 Django 模型
- c# - 使用 MSTest 的测试用例特定日志文件
- r - 使用 `texreg` 根据回归模型中出现的顺序显示变量名称
- php - PHP, Wordpress 死(); 问题
- ruby - 厨师在多行上拆分“执行”命令