React:在useEffect Hook中执行函数以更新状态。使用状态值返回分量A或B

问题描述 投票:0回答:1

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

基于状态,我想返回特定的组件。如果访问错误,则如果是真的,则>

用户第一次进入页面时,它说我刷新页面时访问falsetrue,为什么状态不是第一次更新?

我使用了错误的生命周期方法吗?

Component:

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

[当用户到达此组件时。我想在useEffect挂钩中执行两个函数:-hasError(如果有错误,则返回true)-hasState(如果有状态,则返回true)基于...

reactjs react-router react-hooks lifecycle
1个回答
1
投票

在初始渲染访问状态为假时

© www.soinside.com 2019 - 2024. All rights reserved.