Reactjs redux返回应用程序的新状态
我正在浏览这篇文章 在这篇文章的中途,他们写了这样的东西 最后但并非最不重要的一点是,减速器将状态和动作连接在一起。 它只是一个带有switch语句的纯函数,用于检查 操作类型并返回应用程序的新状态。在我们的文章示例中, 减速器如下所示: 这里,请注意语句返回应用程序的新状态 为了解释这一点,他们展示/写了这个例子Reactjs redux返回应用程序的新状态,reactjs,redux,Reactjs,Redux,我正在浏览这篇文章 在这篇文章的中途,他们写了这样的东西 最后但并非最不重要的一点是,减速器将状态和动作连接在一起。 它只是一个带有switch语句的纯函数,用于检查 操作类型并返回应用程序的新状态。在我们的文章示例中, 减速器如下所示: 这里,请注意语句返回应用程序的新状态 为了解释这一点,他们展示/写了这个例子 const initialState = { articlesById: null, } export default function(state = initialState
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
}
}
[问题]在这里,我无法确定它是如何返回应用程序的新状态的。我所能看到的是,它返回的新对象具有以前的状态,并且是articles by ID
其次,当他们在上面的代码中这样做时,他们的意思是什么
articlesById: action.articlesById
考虑到这是我们的redux商店(从文章中),即我看不到redux商店的任何地方的操作.articlesbyd
附:这是我们博客文章中的redux商店(c)
[问题]在这里,我无法理解它是如何返回应用程序的新状态的。因为我所能看到的是,它返回了新的objectct,它有以前的状态和一些按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
}
}
它返回一个更新状态,并根据操作进行更改。生成了一个新对象以方便检测更改。在获取实际项目后,您需要在reducer接收项目之前调度一个操作,如下所示:
{type:types.articles\u FETCHED,articlesById:[/*articles in here*/]}
在上述示例中,我们没有变异状态只是返回了新对象?如果你能回答,请解释问题的第二部分:)
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
}
}