【问题标题】:What is the best way to update state using useReducer function hooks?使用 useReducer 函数挂钩更新状态的最佳方法是什么?
【发布时间】:2019-09-22 17:24:09
【问题描述】:

我有一个包含以下操作的列表:

  1. 使用useReducer() 函数将对象添加到数组中。
  2. 使用useReducer() 函数从数组中删除一个对象。
  3. 使用useReducer()用旧数组替换新数组 功能。

我需要最好、最安全的方式来更新我的列表。

目前我已经做了类似下面的事情,但它不能正常工作。

const reducer = (state, {type, value}) => {
    switch(type){
        case 'replacenewarray':
            return value;
        case 'additem':
            return {...state, value}
        case 'removeitem':
            return state.filter(item => item.room !== value);
        default:
            return state;
    }
}

我的功能组件如下:

const newArray = [
     {room: 'someroomid1', ....},
     {room: 'someroomid2', ....},
     {room: 'someroomid3', ....}
];

const itemToAdd = {room: 'someroomid4', ....};
const itemToRemoveWithRoomId = 'someroomid2';

export const Group = memo(props=> {

    const [list, setList] = useReducer(reducer, []);

    setList({type: 'replacenewarray', value: newArray});
    setList({type: 'additem', value: itemToAdd});
    setList({type: 'removeitem', value: itemToRemoveWithRoomId});


});

【问题讨论】:

标签: reactjs react-native react-hooks


【解决方案1】:

根据您的代码,您的状态是Array,请确保在从useReducer 返回时保留类型:

const reducer = (state, { type, value }) => {
  switch (type) {
    case 'replacenewarray':
//             v Array as intended
      return value;
    case 'additem':
//             v Fix it to return an array
      return [...state, value];
//             v Object
//    return {...state, value}
    case 'removeitem':
//             v Array as intended
      return state.filter(item => item.room !== value);
    default:
      return state;
  }
};

另外,您必须返回 ReactElementGroup 不会被视为功能组件

export const Group = memo(props => {
  ...
  return <>Some React Element</>;
});

【讨论】:

  • 我无法猜测您是如何阅读list 以及您的应用程序是如何构建的,而且您使用React.memo,有可能在dispatch 之后您的组件甚至没有呈现
猜你喜欢
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2019-08-23
  • 2021-05-30
  • 1970-01-01
相关资源
最近更新 更多