React 页面刷新后根据接口结果跳转:localStorage 和 useEffect 结合使用
在 React 中,你可以使用'localStorage'来存储值,然后在页面刷新时通过请求接口获取结果,并根据结果来进行页面跳转。下面是一个示例代码:
import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
const Home = () => {
const history = useHistory();
useEffect(() => {
const storedValue = localStorage.getItem('myValue');
// 判断是否有存储的值
if (storedValue) {
// 发送请求获取结果
fetch('your-api-url')
.then((response) => response.json())
.then((data) => {
// 根据结果进行页面跳转
if (data.result === 'page1') {
history.push('/page1');
} else if (data.result === 'page2') {
history.push('/page2');
}
})
.catch((error) => {
console.log(error);
});
}
}, [history]);
return <div>Home Page</div>;
};
export default Home;
在上面的示例中,我们使用了 React 的'useEffect'钩子来在页面加载时执行逻辑。首先,我们从'localStorage'中获取存储的值,然后发送请求到 API 来获取结果。根据结果,我们使用'history.push'方法来进行页面跳转。
请注意,这个示例假设你已经使用了 React Router 来进行页面跳转,因此我们使用了'useHistory'钩子来获取'history'对象。如果你没有使用 React Router,你可以使用其他的页面跳转方法来替代。
原文地址: https://www.cveoy.top/t/topic/pdw8 著作权归作者所有。请勿转载和采集!