拥有一个网址为
的React Web应用程序http://localhost/user?id=123&name=SomeName&team=SomeTeam
是否更改ID,名称或团队参数会触发事件?
我知道有componentWillReceiveProps,但似乎只有在它是一个路由参数(即,即
)时才会触发已更改,而不是作为查询字符串参数
答案 0 :(得分:1)
如果您使用反应路由器。您可以使用位置来实现此行为。 看看https://reacttraining.com/react-router/web/api/location
withRouter(Component)
您的组件将在this.props.location.search中获取查询参数,并且当查询参数更改时,组件WillReceiveProps将触发。
答案 1 :(得分:0)
如果您使用react-router v4,则可以直接使用withRouter
HOC来获取位置信息:
import { withRouter } from 'react-router-dom';
const myComponent = ({ listen }) => {
listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
});
return <div>...</div>;
};
export default withRouter(myComponent);
如果您不使用react-router,这是一个JavaScript库,您可以查看https://github.com/ReactTraining/history来管理会话历史记录。
您可以使用history.listen()
功能来检测路线更改。这是一个示例:
import createHistory from "history/createBrowserHistory"
const history = createHistory()
// Get the current location.
const location = history.location
// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
})
// Use push, replace, and go to navigate around.
history.push("/home", { some: "state" })
// To stop listening, call the function returned from listen().
unlisten()
答案 2 :(得分:0)
您可以使用componentDidUpdate
生命周期挂钩
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
console.log('Route Updated');
}
答案 3 :(得分:0)
如果您使用的是 react-router v5。
import { withRouter } from 'react-router-dom';
const myComponent = ({ history }) => {
history.listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
});
return <div>...</div>;
};
export default withRouter(myComponent);