首页 > 解决方案 > 使用钩子更改 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
    }
  };

标签: reactjsreact-nativeredux

解决方案


虽然这样做let newVegeList = state.vegetables,但newVegeList只是您状态的指针,而不是它的浅表副本。因此,你仍然不能改变它,因为你不能改变returnreducer 部分之外的状态。

所以你可以做like let newVegeList = [...state.vegetables],或者直接在return

    return {
        ...state,
        vegetables: state.vegetables.filter((veg, i) => i != action.id)
    }

您还可以发送蔬菜名称或其他任何内容并在以下位置修改检查器filter


推荐阅读