我知道你可以使用 this.props.match.params 访问 url 中的参数 id。我的问题是如何获取用户可能在 url 中操作的更改? 例如:从 props http://localhost:3000/user/3456653/newPage 中的路由器传递的原始 url
用户填写页面并使用 url 参数 id 例如:http://localhost:3000/user/888888/newPage
有没有办法可以在调用 api 来存储数据之前检查参数是否相同?我正在使用 "react-router-dom": "4.2.2"
最佳答案
您可以比较分配给 Route
的组件的 componentDidUpdate
Hook 中的参数,以了解其更改时间。
示例 ( CodeSandbox )
class MyComponent extends Component {
componentDidUpdate(prevProps) {
const prevPathParameter = prevProps.match.params.pathParameter;
const newPathParameter = this.props.match.params.pathParameter;
if (prevPathParameter !== newPathParameter) {
console.log("pathParameter changed!");
}
}
render() {
return <h1> {this.props.match.params.pathParameter}</h1>;
}
}
function App() {
return (
<Router>
<div>
<Link to="/home">Home</Link>
<Link to="/about">About</Link>
<Route path="/:pathParameter" component={MyComponent} />
</div>
</Router>
);
}
关于javascript - ReactJS React Router 获取 url 中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092044/