那是什么" selectedSubreddit"来自Redux Reddit API示例

时间:2016-05-10 00:28:29

标签: redux react-redux

所有

我是Redux的新手,当我按照其Reddit API示例时,有一个代码片段让我非常困惑:

在AsyncApp.js中,有:

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

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

由于

1 个答案:

答案 0 :(得分:2)

该示例使用react-redux中的connect()函数将Redux状态的某些部分和商店的dispatch()函数注入该组件中的props。有关详细信息,请参阅'Usage With React' part of the Redux docs

例如:

<强> 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状态的相应部分注入<App />组件中的props。 mapStateToProps()返回的对象的键对应于注入的道具的名称,相应的值是注入道具的值。

connect()还可以使用第二个参数matchDispatchToProps(),该参数可用于将特定的动作调度函数作为组件中的道具注入。无论您是否向connect()提供任何参数,它都会将您的Redux商店的dispatch()函数注入为dispatch的道具。

这些连接的容器组件从商店接收状态更新,因此当Redux状态发生更改时,连接的容器组件将相应地接收新的道具。