欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

React:Router Nested Route

程序员文章站 2022-06-03 08:24:59
...

Nested Route

可在route中添加route;
需要满足父route的path为子route的前缀,不然子route改变后父route不re-render,页面不会render

Blog.js

                <Switch>
                    <Route path="/new-post" component={NewPost}/>
                    <Route path="/posts" component={Posts}/>
                </Switch>

Posts.js

    return (
      <div>
        <section className="Posts">
          {posts}
        </section>
        <Route path={this.props.match.url+"/:id"} component={FullPost}/>
      </div>
    );u

Dynamic

此时若改变path,则fullpath并不会改变,因为axios设置在didmount中;

FullPath.js
设置componentdidupdate;

componentDidMount(){  //改为mount——不用update,因为每次换都会被remove
        this.loadDatae();
    }

    componentDidUpdate(){
        this.loadDatae();
    }

    loadDatae(){
        if(this.props.match.params.id){
            if( !this.state.loadedPost||(this.state.loadedPost && this.state.loadedPost.id != this.props.match.params.id)){   //保存的为number,得到的为string
                axios.get(`posts/${this.props.match.params.id}`)
                .then(response=>this.setState({loadedPost:response.data}));
            }
        };
    }

    deletePostHandler=()=>{
        axios.delete(`posts/${this.props.match.params.id}`).then(response=>console.log(response));
    }
相关标签: React