【问题标题】:redux returning the new state of Appredux 返回 App 的新状态
【发布时间】: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 */ ] }

标签: reactjs redux


【解决方案1】:

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

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

正如文档解释的那样:“reducer 只是纯粹的函数,它采用前一个状态和一个动作,然后返回下一个状态”

在这里查看:Changes are made with pure functions

编辑:关于您的第二个问题。解释见 cmets:

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
  }
}

【讨论】:

  • 在上面的例子中,我们没有改变状态,只是返回了新的对象?另外,如果你能回答解释问题的第二部分:)
猜你喜欢
  • 2018-09-28
  • 2016-11-20
  • 1970-01-01
  • 2017-12-08
  • 2017-07-12
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多