您正在描述 2 种不同的状态变化。
在第一种情况下,当用户B没有在/job/:id
网页和他点击你得到一个URL变化,这触发了路由器的状态变化的联系,以及传播这种变化通过对您的组件,所以你可以看到评论。
在第二种情况下,当用户B已经在该/job/:id
页面和新的注释来通过,该URL并不需要改变,那么点击链接将不会更改URL,并不会触发的状态变化路由器,因此您将看不到新内容。
我可能会尝试这样的事情(伪代码,因为我不知道你是如何获得新评论或通过 websocket 订阅的):
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
class Home extends React.Component {
render() {
return (
<div>
<h1>The home page</h1>
{/* This is the link that the user sees when someone makes a new comment */}
<Link to="/job/123">See the new comment!</Link>
</div>
);
}
}
class Job extends React.Component {
state = { comments: [] };
fetchComments() {
// Fetch the comments for this job from the server,
// using the id from the URL.
fetchTheComments(this.props.params.id, comments => {
this.setState({ comments });
});
}
componentDidMount() {
// Fetch the comments once when we first mount.
this.fetchComments();
// Setup a listener (websocket) to listen for more comments. When
// we get a notification, re-fetch the comments.
listenForNotifications(() => {
this.fetchComments();
});
}
render() {
return (
<div>
<h1>Job {this.props.params.id}</h1>
<ul>
{this.state.comments.map(comment => (
<li key={comment.id}>{comment.text}</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/job/:id" component={Job} />
</Switch>
</BrowserRouter>,
document.getElementById("app")
);
现在页面将在两种情况下更新。