我正在尝试学习 redux,并偶然发现了这篇文章 hackernoon
一切都很顺利,直到我遇到这个例子
export default function reducer(state = {posts: []}, action) {
switch (action.type) {
case 'Add_USER_POST':
return {
...state,
posts: [
...state.posts,
{
content: action.payload.content,
}
]
};
default:
return state;
}
}
对此给出以下解释..
First, we added a default property posts to our default state and initialised it with [] . Next, we simply added a switch-case block that switches on action.type . Because our action had a type of Add_USER_POST it will be intercepted by the 1st case in our reducer’s switch-case and it will return a fresh object composed out of our existing state and add the newly added post to the posts array.
这里我无法理解以下几行(第一行和最后一行)
首先,我们将默认属性 posts 添加到默认状态并使用 [] 对其进行初始化。
返回一个由现有状态组成的新对象,并将新添加的帖子添加到 posts 数组中
有人可以帮助我用更简单的术语理解上面的代码吗?
[更新]得到了第一点,有人可以向我解释与第二点相关的部分代码的工作原理
return {
...state,
posts: [
...state.posts,
{
content: action.payload.content,
}
]
};
我从上面的代码中了解到,我们返回一个具有当前状态的对象,然后返回一个帖子数组,其中包含我们从这里获取的 state.posts 和 action.payload.content 中的内容
{
type: 'Add_USER_POST',
payload: {
content: 'A quick brown fox jumped over the lazy dog',
}
}
正如我们的文章中所述。
最佳答案
- 此
reducer
函数采用状态和操作参数。如果没有参数传递给 reducer ,它只会返回一个包含空帖子数组的对象。
默认属性:
状态 = {帖子:[]}
设置默认对象作为reducer函数的第一个参数。
- 展开运算符用于组合之前传递的状态、该状态数组中的之前帖子,并使用
action.payload.content
中传递的内容添加新帖子。
文档
关于reactjs - Redux 返回一个由现有状态组成的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51202366/