【发布时间】:2018-07-06 11:31:43
【问题描述】:
我正在阅读 cloudboost talking about redux 的这篇 Medium 文章
这里,在文章的中途,他们写了这样的东西
最后但同样重要的是,reducer 将状态和动作联系在一起。 它只是一个带有 switch 语句的纯函数,用于检查 动作类型并返回应用程序的新状态。在我们的文章示例中, 减速器看起来像这样:
在这里,注意语句return new state of the app
为了解释这一点,他们展示/编写了这个例子
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 store 来自博文 (click here to go through the article)
{ 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"
},..]
}
【问题讨论】:
-
它返回一个更新的状态,并根据操作进行更改。生成一个新对象以轻松检测更改。
-
你需要在获取实际文章后发送一个动作,类似这样,reducer 接收文章之前:
{ type: types.ARTICLES_FETCHED, articlesById: [ /* articles in here */ ] }