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 Router 深入理解Nested Route
本文探讨了React Router中的嵌套路由(Nested Route)概念,指出子路由的路径需是父路由路径的前缀,以确保路由变化时正确渲染页面。通过示例代码Blog.js和Posts.js说明如何实现,并提到了动态路由(Dynamic)的情况。在Dynamic部分,文章提到当路径变化时,由于axios在组件挂载时设置,fullpath不会更新。为解决此问题,建议在ComponentDidUpdate生命周期方法中进行相应处理。
175

被折叠的 条评论
为什么被折叠?



