如何使用 useReducer 更新对象内的数组

hug*_*ana 2 reactjs react-hooks

我正在尝试更新状态对象。其中一项是一个键,其值是一个字符串数组。

我已经能够更新状态,但它不会重新渲染。

const initialState = {
  showUpload: false,
  listItems: parentDirs,
  uploadPath: [],
  fileList: null
};

const reducer = (state, action) => {
  switch (action.type) {
    case "updateListItems":
      return { ...state, listItems: action.payload };
    case "updatePath":
      return {
        ...state,
        uploadPath: [...state.uploadPath, action.payload]
      };
    default:
      return state;
  }
};

const [state, dispatch] = useReducer(reducer, initialState);

const pathFormat = state.uploadPath.join('/')

return (
 <p>{pathFormat}</p>
)

Run Code Online (Sandbox Code Playgroud)

预期的行为是更新状态对象内的数组将触发重新渲染。

小智 6

不完全确定该数组中存在什么,但这里有一个可能有帮助的示例。

您需要的是一个目标标识符。假设您有以下内容:

state = {
cats: [
 {
  name: 'cat1',
  id: 1
 },
  name: 'cat2',
  id: 2
 }
],
// ... rest of state

}
Run Code Online (Sandbox Code Playgroud)

要覆盖 cat 2,您可以执行以下操作:

//           action.type           action.payload
dispatch({ type: 'updateCats', payload: {id: 2, name: 'cat3' }})

// ... and your reducer's switch returns:
case 'updateCats':
  return {
    ...state,
    cats: [...state.cats.filter( cat => id !== payload.id), action.payload]
}
Run Code Online (Sandbox Code Playgroud)

您需要通过删除旧项目并再次添加来重建数组。如何做到这一点取决于您。您可以切片和拼接,或者如果顺序不重要,则示例中使用的过滤方法应该可以工作。