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