How to dispatch Redux action from stateless component when route is loaded?

前端 未结 5 1879
离开以前
离开以前 2020-12-15 17:03

Goal: when loading a react-router route, dispatch a Redux action requesting asynchronic Saga worker to fetch data for the underlying stateless component of

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 17:40

    If you want it to be completely stateless you can dispatch an event when the route is entered using onEnter event.

    
    

    Now you can write you function here provided you either import dispatch in this file or somehow pass it as parameter.

    function dispatchAction(nexState,replace){
       //dispatch 
    }
    

    But this solution I feel is even more dirty.

    The other solution which I could be really efficient is using containers and calling componentDidMount in that.

    import React,{Component,PropTypes} from 'react'
    import {connect} from 'react-redux'
    
    const propTypes = {
     //
    }
    
    function mapStateToProps(state){
    //
    }
    
    class ComponentContainer extends Component {
    
      componentDidMount(){
        //dispatch action
      }
      render(){
        return(
           //your dumb/stateless component . Pass data as props
        )
      }
    } 
    
    export default connect(mapStateToProps)(ComponentContainer)
    

提交回复
热议问题