如何在更改查询参数后触发反应组件重新渲染(没有反应路由器)

问题描述 投票:0回答:2

在下面的 React 组件中,我想在更新后显示 url 查询参数的当前值。像这样的事情使用react-router很简单,但我试图在一个更小的应用程序中手动实现。下面的代码有效地更新了 url,但不会触发重新渲染,因此显示的值永远不会更新。

export default function ExampleComponent() {
    const params = new URLSearchParams(location.search);
    const randomValue = params.get("random");

    function updateRandomValue() {
        const updatedValue = Math.random().toString();
        const newURL = new URL(location.href);
        newURL.searchParams.set("random", updatedValue);
        history.pushState("", "", newURL);
    }

    return (
        <>
            <p>random value is {randomValue || "none"}</p>
            <button onClick={updateRandomValue}>update new random value</button>
        </>
    );
}

我对导航的处理有误吗?是否需要以某种方式涉及

useEffect
?如果没有外部组件和/或使用反应状态,这个功能是不可能的吗?

reactjs html5-history
2个回答
0
投票

我认为您需要将

useEffect
与状态依赖一起使用。也许是这样的:

const [urlParam, setUrlParam] = useState("none");

useEffect(() => {
  const params = new URLSearchParams(location.search);
  const randomValue = params.get("random");
  setUrlParam(randomValue);
}, [urlParam])

然后

<p>random value is {urlParam}</p>


0
投票

经过一番思考后就弄清楚了。仍然需要更好地处理原因,但是将点击处理程序从我的原始代码片段更改为下面的可以解决该错误,而不需要额外的状态:

function updateRandomValue() {
    const updatedValue = Math.random().toString();
    params.set("random", updatedValue);
    location.search = params.toString();
}
© www.soinside.com 2019 - 2024. All rights reserved.