reactjs - React-Redux 提供程序不工作

标签 reactjs redux react-redux

我的项目使用 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))

根据上面的代码以及我之前项目的经验,类别组件的 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

我在这里缺少什么???

最佳答案

您需要在 Category 组件上使用 react-redux 中的 connect 函数,以便它具有 access to dispatch .

export default connect()(Category)

此外,它可能只是针对 SO 进行了简化,但 App 不需要包装在 withRouter 中。仅当您需要将 router props 注入(inject)到组件中时才需要这样做。 Route 会自动为其渲染的任何组件执行此操作,这就是为什么您在 Category 上不需要它。

export default connect(mapStateToProps)(App)

关于reactjs - React-Redux 提供程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47092179/

相关文章:

javascript - 如何使用 React 动态处理多个过滤器?

css - react : Stop click event propagation when using mixed React and DOM events

javascript - 如何在搜索过滤器的 react 选择中添加自定义图标

reactjs - 目标子元素样式组件

reactjs - 当我们可以使用 Provider、useDispatch()、useSelector() 来访问 store、dispatch 和其他重要的 React-Redux 东西时,为什么还要使用 connect() 呢?

javascript - 天气 api key 不起作用

javascript - Redux状态会在路由更改时自行重置(我认为)

javascript - 无法在 ReactJS 中显示图像?

javascript - Reactjs + redux : Sharing reducers across different components

javascript - 如何使用按钮取消选中所有复选框。在子级中输入标签,在父级中输入按钮。 react -表