【发布时间】:2021-01-10 22:44:35
【问题描述】:
我有一个带有下拉列表的表单,当我选择下拉列表时,我将值推送到查询字符串上。当第一次点击带有该查询字符串的 url 时,它将查询字符串参数存储到状态中,然后使用它来填充下拉列表。这一切都按预期工作。我的问题是触发表单以在同一页面上查看查询字符串的更改。
如果我已经在页面上但是然后单击反应路由器链接到同一页面但使用不同的查询字符串参数它不会捕获/看到它已更改。我想知道如何观察查询字符串的变化,或者是否有更好的方法来处理这个问题。
我发现您可以收听 React-Router 打算在后台使用的历史对象,但我在这方面收效甚微,而且我不确定这是否是正确的方法https://github.com/ReactTraining/history/blob/master/docs/getting-started.md
我尝试将以下内容添加到页面,但是当我更改 url 的查询字符串(也称为搜索)时,侦听器似乎永远不会触发。想知道我错过了什么吗?
useEffect(() => {
// Listen for changes to the current location.
console.info("wiring up history listener");
let unlisten = history.listen(({ location, action }) => {
console.info("HISTORY CHANGED", location.search);
console.log(action, location.pathname, location.state);
// Plan was to update my state here if needed
});
return unlisten;
}, []);
使用react-router-dom v6。
【问题讨论】:
-
你将一个空的依赖数组传递给
useEffect,所以它只会在第一次渲染时运行。此外,useEffect 的返回是一个回调,将在触发重新渲染时在卸载之前运行。 -
根据您的需要寻找
useHistory、useParams或useLocation。 They already exist,不用自己动手
标签: javascript reactjs react-router react-router-dom