React:执行useEffect Hook中的函数来更新状态.使用状态值返回组件A或B



当用户到达该组件时。我想在useEffect钩子中执行两个函数:-hasError(如果有错误,则返回true(-hasState(如果存在状态,则返回true(

根据我想要返回的特定组件的状态。如果访问为false,则如果它是真的比

当用户第一次出现在页面上时,它说如果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

将默认状态设置为false,这将是第一次渲染时的值。然后,当触发效果setAccess(hasState(someValue));时,它会在下一次渲染中将访问设置为true。

状态的更改会触发具有新值的重新渲染,但不会中断当前渲染。

你可能会花更多的时间思考你的设置,比如,为什么不用值初始化状态?

const [access, setAccess] = useState(() => hasState(someValue));
const [error, setError] =  useState(() => hasError(someValue));

最新更新