【问题标题】:React-Redux Provider not workingReact-Redux 提供程序不工作
【发布时间】:2017-11-03 09:20:45
【问题描述】:

我的项目使用 React-Redux Provider。

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
  , document.getElementById('root'));

class App extends Component {

  componentDidMount(){

    API.getCategories().then((categories)=>{
      this.props.dispatch(addCategories(categories))
    })

    API.getAllPosts().then(posts => {
      console.log('getAllPosts', posts)
    })
  }

  render() {
    return (
      <div className="App">
        <Route exact path="/" render={()=>{
            return (
              <div>
                {
                  this.props.categories.map((category)=>{
                    return (
                          <Link key={category.name} to={`/category/${category.name}`} params={{category: category.name}} >{category.name}</Link>
                    )
                  })
                }
              </div>
            )
          }}
        />

        <Route path="/category/:category" component={Category} />

      </div>
    );
  }
}



function mapStateToProps(x) {

  return {
    categories: x.categories
  }
}

// export default App;

export default withRouter(connect(
  mapStateToProps,
)(App))

根据上面的代码和我在之前项目中的经验,Category 组件的 this.props 应该有一个 dispatch 方法,我可以使用它来调用操作,但由于某种原因它不存在。

这是我的类别组件:

class Category extends Component {
  componentDidMount(){
    console.log('this.props of Category', this.props)

    var category = this.props.match.params.category

    API.getPosts(category).then((posts)=>{
      console.log('after getPosts', posts)
      this.props.dispatch(addAllPosts(posts))
    })
  }

  render(){
    return <p>Category</p>
  }
}

export default Category

我在这里错过了什么???

【问题讨论】:

  • 仅仅包装一个provider元素是不够的,你需要在你的category组件周围创建一个容器组件,将状态映射到props并传递dispatch函数。请参阅文档:redux.js.org/docs/basics/UsageWithReact.html

标签: reactjs redux react-redux


【解决方案1】:

您需要在您的Category 组件上使用来自react-reduxconnect 函数,以便它具有access to dispatch

export default connect()(Category)

此外,它可能只是简化为 SO,但 App 不需要包含在 withRouter 中。仅当您需要将路由器道具注入组件时才需要这样做。 Route 会自动为它呈现的任何组件执行此操作,这就是为什么您在 Category 上不需要它。

export default connect(mapStateToProps)(App)

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2020-11-20
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多