"selectedSubreddit" 在 Redux Reddit API 示例中来自哪里

Where does that "selectedSubreddit" come from in Redux Reddit API example

全部:

我是 Redux 的新手,当我关注它的 Reddit API 示例时,有一个代码片段让我很困惑:

在AsyncApp.js中,有:

componentDidMount() {
    const { dispatch, selectedSubreddit } = this.props
    dispatch(fetchPostsIfNeeded(selectedSubreddit))
  }

我想知道 dispatch 和 selectedSubreddit 在哪里绑定到 this.props?

谢谢

该示例使用 react-redux to inject certain parts of the Redux state and the store's dispatch() function as props in that component. See the 'Usage With React' part of the Redux docs 中的 connect() 函数以获取更多信息。

例如:

App.js:

export class App extends Component {
  //...
}

function mapStateToProps(state) {
  const { selectedReddit, postsByReddit } = state
  const {
    isFetching,
    lastUpdated,
    items: posts
  } = postsByReddit[selectedReddit] || {
    isFetching: true,
    items: []
  }

  return {
    selectedReddit,
    posts,
    isFetching,
    lastUpdated
  }
}

export default connect(mapStateToProps)(App)

这里的 connect() 函数使用上面的 mapStateToProps() 函数将 Redux 状态的适当部分作为 props 注入到 <App /> 组件中。 mapStateToProps()返回的对象的key对应注入的props名称,对应的value就是注入props的值。

connect() 也可以接受第二个参数,matchDispatchToProps(),它可以用来将特定的动作调度函数作为 props 注入到你的组件中。无论您是否向 connect() 提供任何参数,它都会将您的 Redux 商店的 dispatch() 函数作为一个名为 dispatch.

的道具注入

这些连接的容器组件从商店接收状态更新,所以当你的 Redux 状态改变时,连接的容器组件将相应地接收新的道具。