reactjs - React:在 useEffect Hook 中执行函数来更新状态。使用状态值返回组件 A 或 B
问题描述
当用户到达此组件时。我想在 useEffect 挂钩中执行两个函数: - hasError(如果有错误则返回 true) - hasState(如果有状态则返回 true)
根据我想返回特定组件的状态。如果访问是假的比 如果是真的比
用户第一次进入页面时,它说如果false
我刷新页面时访问它是true
为什么状态第一次不更新?
我是否使用了错误的生命周期方法?
零件:
const ContinueRouteComponent = () => {
const dispatch = useDispatch();
// const [access, setAccess] = useState(false);
// const [error, setError] = useState(false);
const query = useQuery();
//check if user has valid state
const hasState = (stateId: string) => {
// No state is given in the uri so no access
if(stateId === null) {
return false;
}
// You have a state in the uri but doesn't match the localstorage
return localStorage.getItem(stateId) !== null;
};
const hasError = (error: string) => {
return error !== null;
};
const [access, setAccess] = useState(() => hasState(query.get("state")));
const [error, setError] = useState(() => hasError(query.get("error")));
useEffect(() => {
dispatch(fetchResources());
},[]);
if(error){
let errorType = query.get("error");
let errorDescription = query.get("error_description");
return <Redirect exact={true} to={{
pathname: '/error',
state: {
error: errorType,
description: errorDescription
}
}} />;
}
if(access){
const retrievedStorage = JSON.parse(localStorage.getItem(query.get("state")));
localStorage.removeItem(query.get("state"));
return <Redirect exact to={retrievedStorage} />
} else {
return <Redirect to="/"/>
}
};
export default ContinueRouteComponent
解决方案
初始渲染访问状态为假
您将默认状态设置为 false,这将是第一次渲染时的值。然后,当您触发效果时setAccess(hasState(someValue));
,它会将访问权限设置为在下一次渲染时为真。
状态的变化会触发使用新值的重新渲染,但不会中断当前的渲染。
您可能会花更多时间考虑您的设置,例如,为什么不使用值初始化状态?
const [access, setAccess] = useState(() => hasState(someValue));
const [error, setError] = useState(() => hasError(someValue));
推荐阅读
- algorithm - 表示数字的算法
- powershell - 如何在 PowerShell 脚本中以“运行提升”(不以管理员身份运行)的方式执行 .exe
- json - 在 PowerShell 中了解 NewtonSoft
- sql - 如何更新表(MySQL)中新字段的记录(来自列表)?
- css - CCS 菜单从主页更改
- node.js - 如何使用 pm2.config.js 生态系统部署不同数量的 pm2 fork 模式实例
- r - 我如何设置我的工作字典,以便其他人可以从 USB 运行我的代码
- c - 将令牌存储在数组中
- python - 如何使用 OpenCV 和 Python 从图像中分离手写文本?
- elasticsearch - 如何在 Elastic High Level Rest Client 中使用 search_after 进行分页