我遇到問題。我正在創建一個反應減少的小應用程序。React Redux - 在連接組件中使用mapDispatchToProps時,如何在componentDidMount上分派動作
在下面的代碼中是我的app.js組件。直到我嘗試在connect中使用mapDispatchToProps函數時它工作正常。問題是我無法再調用componentDidMount上的調度動作。 componentDidMount中的操作以及現在位於mapStateToProps上的操作需要在comoponentDidMount上調用。如何做到這一點的任何線索?
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 {
\t \t state = {
\t \t \t posts: []
\t \t }
\t \t componentDidMount() {
\t \t \t const { dispatch, selectedCategory, fetchCategories, fetchPosts} = this.props
\t \t //dispatch(fetchCategoriesIfNeeded(selectedCategory))
\t \t //dispatch(fetchPostsIfNeeded(selectedCategory))
\t \t }
\t \t orderByScoreAsc = (posts) => {
\t return posts.sort(sortAsc('voteScore'))
\t }
\t \t orderByScoreDesc = (posts) => {
\t return posts.sort(sortDesc('voteScore'))
\t }
\t \t render() {
\t \t const { navCategories, posts } = this.props
\t return (
\t <div>
\t <HeaderNavigation navCategories = {navCategories} />
\t <Route exact path="/" render={()=>(
\t <TableBody
\t \t showingPosts={posts}
\t />)}
\t />
\t
\t
\t </div>
\t );
\t }
}
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)