[英]Using spread syntax in Reducer
I am trying to use the spread syntax to update the state inside the reducer 我正在尝试使用传播语法来更新reducer内部的状态
The state consists of an object, and the object has an array, 状态由一个对象组成,并且该对象具有一个数组,
I would like to update all properties in the object, except for the array, which I would like to add the next state elements at the end. 我想更新对象中除数组之外的所有属性,我想在末尾添加下一个状态元素。 For example,
例如,
For example, if the state is 例如,如果状态为
{
id: 4,
amount: 10,
arr: [
name: "peter",
name: "john"
]
}
and the action 和动作
{
id: 7,
amount: 7,
arr: [
name: "sally",
name: "maria"
]
}
I would like to get as a result of using the spread syntax 我想得到使用spread语法的结果
{
id: 7,
amount: 7,
arr: [
name: "peter",
name: "john",
name: "sally",
name: "maria"
]
}
taking the id and amount of the action, and concatenating the array 采取行动的ID和数量,并连接数组
Thank you 谢谢
Simply keep spreading props. 只需保持传播道具。
const INITIAL_STATE = { id: 4, amount: 10, arr: [ { name: "peter" }, { name: "john" }, ], } function reducer(state = INITIAL_STATE, action) { switch (action.type) { default: return state case 'ANY_ACTION': return { ...state, ...action.payload, arr: [ ...(state.arr || []), ...action.payload.arr, ] } } } const action = { type: 'ANY_ACTION', payload: { id: 7, amount: 7, arr: [ { name: "sally" }, { name: "maria" }, ] } } const state = reducer(undefined, action) console.log(state)
First of all your structure is invalid, the correct structure would look like 首先您的结构无效,正确的结构看起来像
{
id: 4,
amount: 10
data: [
{name: "peter"},
{name: "john"}
]
}
and then you could use spread operator to update state assuming action.payload
to be 然后您可以使用传播运算符来更新状态,并假设
action.payload
为
{
id: 7,
amount: 7
data: [
{name: "sally"},
{name: "maria"}
]
}
like 喜欢
case 'WHATEVER_ACTION':
return {
...state,
id: action.payload.id,
amount: action.payload.amount,
data: [...state.data, ...action.payload.data]
}
Check the documentation of Spread syntax to understand its usage more 查看Spread语法的文档以进一步了解其用法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.