首页 > 解决方案 > 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

标签: reactjsreact-routerreact-hookslifecycle

解决方案


初始渲染访问状态为假

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

状态的变化会触发使用新值的重​​新渲染,但不会中断当前的渲染。

您可能会花更多时间考虑您的设置,例如,为什么不使用值初始化状态?

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

推荐阅读