redux 返回应用的新状态



我正在通过cloudboost阅读Medium的这篇文章,谈论redux

在这里,在文章中途,他们写了这样的东西

最后但并非最不重要的一点是,化简器将状态和行动联系在一起。 它只是一个纯函数,带有一个 switch 语句来检查 操作类型并返回应用的新状态。在我们的文章示例中, 减速器如下所示:

在这里,请注意返回应用新状态的语句

为了解释这一点,他们展示/编写了这个例子

const initialState = {
articlesById: null,
}
export default function(state = initialState, action) {
switch (action.type) {
case types.ARTICLES_FETCHED:
return {
...state,
articlesById: action.articlesById
}
default:
return initialState
}
}

[问题]在这里,我无法弄清楚它是如何返回应用程序的新状态的。对于我所能看到的,它正在返回具有先前状态的新对象以及按 ID 撰写的文章。那么首先有人可以解释一下这个声明吗?

其次,当他们在上面的代码中这样做时,他们是什么意思

articlesById: action.articlesById

考虑到这是我们的 redux 存储(来自文章(,即我在任何地方都看不到 redux 存储action.articlesById

Ps:这是我们来自博客文章的redux商店(点击这里浏览文章(

{ type: 'ARTICLES_FETCHED', 
payload: [{
"id": 314,
"title": "6 innovative apps utilizing the ethereum network",
"source": "Investopedia‎",
"link": "http://www.investopedia.com/news/6-innovative...",
"date": "1500523200",
"type": "msm"
},
{
"id": 893,
"title": "what is plasma and how will it strengthen...",
"source": "Investopedia‎",
"link": "http://www.investopedia.com/news/what-plasma-and...",
"date": "1502856000",
"type": "msm"
},..] 
}

[问题] 在这里,我无法弄清楚它是如何返回应用程序的新状态的。对于我所能看到的,它正在返回具有先前状态的新对象,并且是按ID撰写的文章。那么首先有人可以解释一下这个声明吗?

[答案]你返回一个新对象,没错。这意味着你不直接操作状态(不要改变状态(,而是返回一个新的状态(对象(。 这是函数式编程的一个概念,称为纯函数,是Redux的关键概念之一。

正如文档所解释的那样:"化简器只是接受上一个状态和一个动作,然后返回下一个状态的纯函数">

检查此处:使用纯函数进行更改

编辑:关于你的第二个问题。有关解释,请参阅评论:

const initialState = {
articlesById: null,
}
export default function(state = initialState, action) {
switch (action.type) {
// If the action type is ARTICLES_FETCHED, you return a new state
case types.ARTICLES_FETCHED: 
// You are returning a new object created wit literal syntax `{}`
return {
...state, // You are using the spread operator `...` to get all the properties of `state`
articlesById: action.articlesById // You are setting the property `articlesById` of the new object to the property `articlesById` of your action (if defined)
}
default: // If the action type is not ARTICLES_FETCHED, then you return the initial state without any change
return state; // I've made a change here, you can just return `state`, because your state has the default value of initialState
}
}

最新更新