【问题标题】:Problem updating a list with redux toolkit使用 redux 工具包更新列表时出现问题
【发布时间】:2022-10-23 16:32:32
【问题描述】:
// './file_1'

import { createSlice } from '@reduxjs/toolkit';

export const array = createSlice({
    name: 'array',
    initialState: {
      value: []
    },
    reducers:{
      append(state, a) {
        state.value.push(a)
      }
    }
});

export const { append } = array.actions;
export default array.reducer;

我也更新了商店,所以那边没问题

'/.file_2'
import { useSelector, useDispatch } from 'react-redux';
import { append } from './file_1';
const dispatch = useDispatch()
let x = 5
dispatch(append(x));

引发此错误: 对象作为 React 子级无效(找到:带有键 {type, payload} 的对象)。如果您打算渲染一组子项,请改用数组。

【问题讨论】:

  • 显示错误指向的代码...返回 JSX 或从组件函数返回值的某处
  • 你的意思是错误下的堆栈?我是菜鸟。

标签: javascript reactjs redux redux-toolkit


【解决方案1】:

“a”是一个对象。对象看起来像这样 -> {action: ..., payload: ...} 所以你需要像这样访问它-> a.payload

【讨论】:

  • 你能告诉我应该如何重写上面的代码吗?
【解决方案2】:

问题

问题是代码试图渲染一个无效的 JSX 对象。

由于您没有关于数组的错误,我假设您正确映射它,如下所示:

const array = useSelector(state => state.array);

...

return (
  ...
  {array.map(el => (
    <div>{el}</div> // <-- error, can't render object!!
  ))}
);

错误是error: Objects are not valid as a React child (found: object with keys {type, payload}),这很明显是动作对象被分派到 Redux 存储并保存到状态中。

export const array = createSlice({
  name: 'array',
  initialState: {
    value: []
  },
  reducers:{
    append(state, a) {
      state.value.push(a) // <-- `a` is action object `{ type: 'append', payload: 5 }`
    }
  }
});

解决方案

我确定你的意思是保存只是有效载荷值而不是全部的action 对象,因为调度的值x 是原始数字类型。

const dispatch = useDispatch()
let x = 5
dispatch(append(x));

更新 reducer 函数以解压有效负载以保存到状态。

export const array = createSlice({
  name: 'array',
  initialState: {
    value: []
  },
  reducers:{
    append(state, action) {
      state.value.push(action.payload); // 5
    }
  }
});

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 2018-03-05
    • 2023-01-16
    • 2021-06-17
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    相关资源
    最近更新 更多