带有 React-Native 和 mapStateToProps 的 Redux

Redux with React-Native and mapStateToProps

我读过这个话题。

它说 props 不同于状态,理想情况下 props 不应在其组件中更改,而应仅由其父组件更改。

然而,react-redux 中的 mapStateToProps 函数将 Redux 中的状态映射到 React 组件的 props,这基本上是在 Redux 状态被 Redux 操作更改时更改 React 组件的 props。

这对我来说没有意义。似乎它应该是 mapStateToStates 而不是并将 Redux 状态映射到 React 组件的状态。

我是不是漏掉了什么?

It says that props are different from states and ideally props should not be change in its component and only should be changed by its parent component.

这里的State是指组件的内部状态,组件可以通过.setState()在内部改变。

However, mapStateToProps function in react-redux maps states in Redux to props of a React components, which is basically changing props of a React component when Redux state is changed by an Redux action.

这里的状态指的是redux store,一个外部状态。 react-redux 的 connect 方法创建了一个 HOC - 高阶组件(一个知道商店状态变化的组件)。 HOC 包装了哑反应组件,它不知道商店。使用 mapStateToProps HOC 映射来自外部状态的数据,并通过 props 将其注入 React 组件。

redux store 中的状态 -> HOC 中的 mapStateToProps -> props 传递给哑组件

所以 HOC 是父组件,dumb 组件是子组件。父组件向子组件注入新的 props,第一个断言 "props should not be change in its component and only should be changed by its parent component" 没有被违反。


备注:

  1. 有关高阶分量的更多信息,请参阅 Dan Abramov 关于 Presentational and Container Components 的文章。

  2. 了解 react-redux connect 的工作原理 - 在在线免费课程中,Getting Started with Redux,Dan Abramov 展示了如何从头开始构建 connect(第 22-29 课)

  1. state 这里的 mapStateToProps 表示 stateReduxStore.

  2. 它将Reduxstate映射到ReactComponentprops。不一定将道具映射到状态,例如Pure Component

mapStateToProps 使用 react-redux connect () 函数将状态作为 props 传递给组件。将 connect() 函数视为包装器组件,它将 props 传递给子组件。

                    mapStateToProps
connect (state) ----------------------->  component(props)