我想将state.name
设置为";Alex";和age
加一后点击登录功能,并设置电子邮件为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 Toolkit。
您似乎正在组件中选择此state.user.value
状态并呈现组成部分,即value.name
、value.age
和value.email
。在调度login
操作时将state.user.value.email
更新为具有{ email: 'example@gmail.com' }
的有效负载值之前,这是可以的。这使得value.email
成为一个对象并且不可绘制。
使用要保存到状态的精确有效载荷值调度login
操作:
<button
onClick={() => {
dispatch(login('example@gmail.com'));
}}
>
Login
</button>
或者在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}
</>