【发布时间】:2020-08-18 10:18:44
【问题描述】:
如果我们点击帖子链接,blog.js 的执行将从这里开始。
我在 post.js 中调用了 history.push 两次,但是 new-post 没有呈现,就像在 newpost.js 中指定的控制台日志一样。 ComponentDidMount 和 render 方法没有执行,但是它正在执行posts.js中的控制台日志。
博客.js:
class Blog extends Component {
render () {
return (
<div className="Blog">
<ul>
<li>
<Link to="/posts" exact>Posts</Link>
</li>
<li>
<Link to="/new-post">New Post</Link>
</li>
</ul>
<Switch>
<Route path="/new-post" render={()=>(<Newpost/>)}/>
<Route path="/posts" component={Posts}/>
<Route path="/" exact component={Posts}/>
<Route render={()=><h1>Not Found</h1>}/>
</Switch>
</div>
);
}
}
Posts.js(当我们在 blog.js 中调用帖子链接时呈现):
class Posts extends Component {
componentDidMount(){
console.log("render");
});
}
postselect = (id) => {
this.props.history.push('/new-post');
console.log("hello");
console.log("hello");
console.log("hello");
console.log("hello");
this.props.history.push('/posts');
}
render()
{
console.log("posts render");
return(
<div>
<button onClick={this.postselect}>submit</button>
</div>);
}
}
newposts.js(如果我们调用这个路由应该渲染):
class NewPost extends Component {
componentDidMount(){
console.log("hellonewpost");
}
render () {
console.log("newpost render");
return (
<div className="NewPost">
...
</div>
);
}
}
【问题讨论】:
-
试试这个。
-
同样的事情发生了......没有变化
-
可能是因为你在 switch 之外使用了 Link 元素?
-
用Router组件包裹再试一次
标签: reactjs react-redux react-router react-hooks react-state