gpt4 book ai didi

reactjs - 使用后退按钮时,React JS 页面不断刷新

转载 作者:行者123 更新时间:2023-12-04 15:07:16 25 4
gpt4 key购买 nike

我有 2 个 React JS 页面(A 和 B),当我从 A->B 返回到 A 时,页面 A 每次都会刷新。我的印象是页面没有被破坏。 StackOverflow 上的所有相关问题似乎都与相反的问题有关。
页面刷新的原因是尽管使用 useState() 来防止这种情况,但在按下后退按钮时会调用 useEffect()。我什至尝试用“props.id”参数(永远不会改变)替换“refresh”。见下面的代码:
这是我到页面 A 的代码:

import { useHistory, useParams } from "react-router-dom";
import React, { useState, useEffect, useRef } from "react";
import { Link } from "react-router-dom";

export default function Test(props) {
const [refresh, setRefresh] = useState(false);

useEffect(() => {
console.log("useEffect called: "+refresh);
setRefresh(true);
},[refresh]);

return (
<>
Hello from Test
<Link to="/test2">Test me</Link>
</>
);
}
我正在使用 react-router-dom: "^5.1.2", 并从 "react-router-dom"导入 { BrowserRouter as Router };在 App.js 中并指定:
  <Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/test">
<Test id="1"/>
</Route>
<Route exact path="/test2">
<Test2 />
</Route>
.....
有谁知道如何防止在返回页面时触发 useEffect() ?实际页面 A 使用 REST 调用获取并显示一长串项目,我不希望每次用户加载页面 B 以查看项目然后返回页面时都刷新页面。

最佳答案

解决方案1(正确方法)

Use Stateless components and have a common super state (Redux will be of great assistance), and bind you page/data to common state so even if the state changes, the page will always render the current state creating an illusion of page retaining the state (I used it to run large queries and store progress/result in redux so even if I open another page and come back then also I see query in progress or result).


但是,我不确定您的用例是什么。
解决方案2(方法略有错误)
使用 React.memo,当你不想更新你认为是静态的组件时可以使用它
对于功能组件:
 const Mycomponents = React.memo(props => {   
return <div>
No updates on this component when rendering, use useEffect to verify too
</div>;
});
你不应该在这种方法中定义任何方法/功能/动态计算只是为了避免获得不规则的数据

关于reactjs - 使用后退按钮时,React JS 页面不断刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65878920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com