React router Link not causing component to update within nested routes

后端 未结 5 1406
栀梦
栀梦 2021-02-07 14:46

This is driving me crazy. When I try to use React Router\'s Link within a nested route, the link updates in the browser but the view isn\'t changing. Yet if I refresh the page t

5条回答
  •  被撕碎了的回忆
    2021-02-07 14:55

    I got stuck on this also in React 16.

    My solution was as follows:

    componentWillMount() {
        const { id } = this.props.match.params;
        this.props.fetchCategory(id); // Fetch data and set state
    }
    
    componentWillReceiveProps(nextProps) {
        const { id } = nextProps.match.params;
        const { category } = nextProps;
    
        if(!category) {
            this.props.fetchCategory(id); // Fetch data and set state
        }
    }
    

    I am using redux to manage state but the concept is the same I think.

    Set the state as per normal on the WillMount method and when the WillReceiveProps is called you can check if the state has been updated if it hasn't you can recall the method that sets your state, this should re-render your component.

提交回复
热议问题