我遇到了这个问题。我正在使用 React Redux 创建一个小应用程序。

下面的代码是我的 app.js 组件。它工作正常,直到我尝试使用 connect 内的 mapDispatchToProps 函数。问题是我无法再调用 componentDidMount 上的调度操作。之前在 componentDidMount 中以及现在在 mapStateToProps 上的操作需要在 cooponentDidMount 上调用。有任何关于如何做到这一点的线索吗?

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)

请您参考如下方法:

我将您的代码修改为我认为可行的内容。我也留下了评论。

class App extends Component { 
 
  state = { 
    posts: [] 
  } 
 
  componentDidMount() { 
    // no need to use dispatch again. Your action creators are already bound by  
    // mapDispatchToProps.  Notice also that they come from props 
    const { selectedCategory, fetchCategoriesIfNeeded, fetchPostsIfNeeded} = this.props; 
    fetchCategoriesIfNeeded(selectedCategory); 
    fetchPostsIfNeeded(selectedCategory); 
  } 
 
  //... the same 
} 
 
function mapStateToProps ( state ) { 
  //... the same 
} 
 
function mapDispatchToProps (dispatch) { 
  // when arguments match, you can pass configuration object, which will  
  // wrap your actions creators with dispatch automatically. 
  return { 
    orderPost, 
    fetchCategoriesIfNeeded, 
    fetchPostsIfNeeded, 
  } 
} 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!