How to fetch the new data in response to React Router change with Redux?

前端 未结 3 671
借酒劲吻你
借酒劲吻你 2020-12-12 16:24

I\'m using Redux, redux-router and reactjs.

I\'m trying to make an app where I fetch information on route change, so, I\'ve something like:



        
相关标签:
3条回答
  • 2020-12-12 16:39

    Now, my question is, Is this really necessary or just a way to keep the architecture react-agnostic? Can I just fetch the information I need from react componentDidMount() and componentDidUpdate() instead?

    You can totally do that in componentDidMount() and componentWillReceiveProps(nextProps).
    This is what we do in real-world example in Redux:

    function loadData(props) {
      const { fullName } = props;
      props.loadRepo(fullName, ['description']);
      props.loadStargazers(fullName);
    }
    
    class RepoPage extends Component {
      constructor(props) {
        super(props);
        this.renderUser = this.renderUser.bind(this);
        this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
      }
    
      componentWillMount() {
        loadData(this.props);
      }
    
      componentWillReceiveProps(nextProps) {
        if (nextProps.fullName !== this.props.fullName) {
          loadData(nextProps);
        }
    
      /* ... */
    
    }
    

    You can get more sophisticated with Rx, but it's not necessary at all.

    0 讨论(0)
  • 2020-12-12 16:45

    1) dispatching optimistic request actions on route changes, i.e. BrowserHistory.listen(location => dispatch(routeLocationDidUpdate(location)));

    2) Async Actions: http://redux.js.org/docs/advanced/AsyncActions.html

    0 讨论(0)
  • 2020-12-12 16:46

    I've did this with custom binding on plain router onEnter/onLeave callback props like this:

    const store = configureStore()
    
    //then in router
    <Route path='/myRoutePath' component={MyRouteHandler} onEnter={()=>store.dispatch(myRouteEnterAction())} />
    

    It's a bit hacky but works, and I don't know better solution right now.

    0 讨论(0)
提交回复
热议问题