我遇到了这个问题 . 我正在用react redux创建一个小应用程序 .
在下面的代码是我的app.js组件 . 它工作正常,直到我尝试在connect中使用mapDispatchToProps函数 . 问题是我无法再调用componentDidMount上的调度操作 . 需要在comoponentDidMount上调用componentDidMount中现在位于mapStateToProps上的操作 . 有关如何做到的任何线索?
import React, { Component } from 'react';
import './App.css';
import '../../node_modules/bootstrap/less/bootstrap.less';
import { Route } from 'react-router-dom'
import * as ReadableAPI from '../ReadableAPI'
import HeaderNavigation from './HeaderNavigation';
import TableBody from './TableBody';
import { connect } from 'react-redux';
import sortAsc from 'sort-asc';
import sortDesc from 'sort-desc';
import {
selectedCategory,
fetchCategoriesIfNeeded,
fetchPostsIfNeeded,
invalidateSubreddit,
orderPost
} from '../actions'
class App extends Component {
state = {
posts: []
}
componentDidMount() {
const { dispatch, selectedCategory, fetchCategories, fetchPosts} = this.props
//dispatch(fetchCategoriesIfNeeded(selectedCategory))
//dispatch(fetchPostsIfNeeded(selectedCategory))
}
orderByScoreAsc = (posts) => {
return posts.sort(sortAsc('voteScore'))
}
orderByScoreDesc = (posts) => {
return posts.sort(sortDesc('voteScore'))
}
render() {
const { navCategories, posts } = this.props
return (
<div>
<HeaderNavigation navCategories = {navCategories} />
<Route exact path="/" render={()=>(
<TableBody
showingPosts={posts}
/>)}
/>
</div>
);
}
}
function mapStateToProps ( state ) {
const { categories, posts } = state
return {
navCategories: categories.items,
posts: posts.items
}
}
function mapDispatchToProps (dispatch) {
return {
changeOrder: (data) => dispatch(orderPost(data)),
fetchCategories: (data) => dispatch(fetchCategoriesIfNeeded(data)),
fetchPosts: (data) => dispatch(fetchPostsIfNeeded(data))
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App)
3 回答
我将您的代码修改为我认为可行的代码 . 我也留下了评论 .
在map for dispatch中你有fetchCategories / fetchPosts所以你需要像这样调用它们:
你有这个:
所以你需要从你的道具调用fetchCategories / fetchPosts而不是fetchCatIfneeded / fetchPostsifneeded
你没有 . mapDispatchToProps正是您尝试在组件中执行的操作 . 您可以调用通过connect提供给组件的方法,而不是调用分派 . 在你的情况下: