旧标题:React useEffect不在页面重新加载上运行
useEffect(()=>{console.log("I ran")}, []) // should run once
如果我导航到包含该组件的页面,它将运行,但是如果我重新加载该页面,则不会再次运行。
即使重新加载页面,如何获得运行效果? 编辑:重新载入页面对我来说意味着按F5
const Lobby = () => {
const [result, setResult] = useState();
const { joinedLobby, setCurJoinedLobby } = useContext(JoinedLobbyContext);
useEffect(() => {
if (joinedLobby !== undefined)
sessionStorage.setItem('joinedLobby', JSON.stringify(joinedLobby));
const storedJoinedLobby =
sessionStorage.getItem('joinedLobby') !== null
? JSON.parse(sessionStorage.getItem('joinedLobby'))
: undefined;
if (joinedLobby === undefined && storedJoinedLobby !== undefined) {
setCurJoinedLobby(storedJoinedLobby);
}
if (joinedLobby === undefined) return setResult(<div>Bad Link</div>);
setResult(<div>Some stuff here</div>);
}, []); // will be [joinedLobby] in the future
return <div>{result}</div>
};
Cut down example, clone and run locally to get session store
答案 0 :(得分:0)
useEffect
在每个渲染器上运行 。
因此,在渲染将不起作用之前,渲染在useEffect
中依赖的设置数据。
我能想到的最好的解决方案是设置状态,以跟踪是否是第一次渲染组件,以便组件的初始返回不依赖于{{ 1}}。
答案 1 :(得分:0)
我不确定您是否假设useEffect
不在运行,因为您遇到result is undefined
错误。但是,如果是这种情况,则将需要为result
const分配默认值,因为useEffect
在第一次尝试渲染后正在运行。
所以
const [result, setResult] = useState({})
无论您是从某个地方导航还是重新加载,这始终有效。无论如何,您都在useEffect中设置了正确的状态。
https://codesandbox.io/s/busy-williams-j5spe?file=/src/Lobby.jsx