当使用钩子改变Redux状态时,React Native模态不会更新

问题描述 投票:0回答:1

我在我的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
    }
  };
reactjs react-native redux
1个回答
1
投票

[let newVegeList = state.vegetables这样做时,newVegeList只是状态的指针,而不是状态的浅表副本,您仍然无法对其进行突变,因为您无法对化简器的return部分进行状态突变。

所以您可以像let newVegeList = [...state.vegetables]一样直接使用,也可以直接在返回处使用


    return {
        ...state,
        vegetables: state.vegetables.splice(action.id,1)
    }
© www.soinside.com 2019 - 2024. All rights reserved.