React router Link not causing component to update within nested routes

后端 未结 5 1411
栀梦
栀梦 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

    componentWillReceiveProps is the answer to this one, but it's a little annoying. I wrote a BaseController "concept" which sets a state action on route changes EVEN though the route's component is the same. So imagine your routes look like this:

    
    
    
    

    So then a BaseController would check the route update:

    import React from "react";
    
    /**
     * conceptual experiment
     * to adapt a controller/action sort of approach
     */
    export default class BaseController extends React.Component {
    
    
        /**
         * setState function as a call back to be set from
         * every inheriting instance
         *
         * @param setStateCallback
         */
        init(setStateCallback) {
            this.setStateCall = setStateCallback
            this.setStateCall({action: this.getActionFromPath(this.props.location.pathname)})
        }
    
        componentWillReceiveProps(nextProps) {
    
            if (nextProps.location.pathname != this.props.location.pathname) {
                this.setStateCall({action: this.getActionFromPath(nextProps.location.pathname)})
            }
        }
    
        getActionFromPath(path) {
    
            let split = path.split('/')
            if(split.length == 3 && split[2].length > 0) {
                return split[2]
            } else {
                return 'index'
            }
    
        }
    
        render() {
            return null
        }
    
    }
    

    You can then inherit from that one:

    import React from "react"; import BaseController from './BaseController'

    export default class TestController extends BaseController {
    
    
        componentWillMount() {
            /**
             * convention is to call init to
             * pass the setState function
             */
            this.init(this.setState)
        }
    
        componentDidUpdate(){
            /**
             * state change due to route change
             */
            console.log(this.state)
        }
    
    
        getContent(){
    
            switch(this.state.action) {
    
                case 'index':
                    return  Index action 
                case 'anything':
                    return Anything action route
                case 'edit':
                    return Edit action route
                default:
                    return 404 I guess
    
            }
    
        }
    
        render() {
    
            return (

    Test page

    {this.getContent()}

    ) } }

提交回复
热议问题