如何在redux-toolkit中存储action.payload

4xrmg8kj  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(115)

我想在单击登录功能后将state.name设置为“Alex”和age加1,并将电子邮件设置为action.payload
这是我的用户状态切片

const userSlice = createSlice({
  name: "user",
  initialState: { value: { name: "", age: 0, email: "" } },
  reducers: {
    login: (state, action) => {
      state.value.name = "Alex"
      state.value.age = state.value.age + 1
      state.value.email = action.payload
    }, 
  }
})

这是我的useDispatch

function Login() {
  const dispatch = useDispatch()

  return (
    <div>
      <button
        onClick={() => {
          dispatch(login({ email: 'example@gmail.com' }))
        }}
      >
        Login
      </button>
    </div>
  )
}

发生错误:Objects are not valid as a React child (found: object with keys {email}). If you meant to render a collection of children, use an array instead.
我正在使用Redux工具包。

bq3bfh9z

bq3bfh9z1#

看起来你很可能在一个组件中选择了state.user.value状态,并呈现了组成部分,即value.namevalue.agevalue.email。这是很好的,直到你在调度login动作时更新state.user.value.email,使其具有{ email: 'example@gmail.com' }的有效负载值。这使得value.email成为一个对象,并且不可呈现。
使用您要保存到state中的 * 确切 * 有效负载值来调度login操作:

<button
  onClick={() => {
    dispatch(login('example@gmail.com'));
  }}
>
  Login
</button>

或者在case reducer中从有效负载中正确地解包email属性:

const userSlice = createSlice({
  name: "user",
  initialState: {
    value: {
      name: "",
      age: 0,
      email: ""
    }
  },
  reducers: {
    login: (state, action) => {
      state.value.name = "Alex";
      state.value.age = state.value.age + 1;
      state.value.email = action.payload.email;
    },
  }
});

我还建议简化状态,以取消嵌套要存储的实际值。
示例:

const userSlice = createSlice({
  name: "user",
  initialState: {
    name: "",
    age: 0,
    email: ""
  },
  reducers: {
    login: (state, action) => {
      state.name = "Alex";
      state.age = state.age + 1;
      state.email = action.payload; // { payload: 'example@gmail.com' }
    },
  }
});

...

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

...

<>
  Name: {user.name}
  Age: {user.age}
  Email: {user.email}
</>

相关问题