首页 > 解决方案 > 为什么 ASYNC AWAIT 在反应中的使用效果不好

问题描述

我试图获取用户位置,然后使用该位置返回相关数据以获取位置。

但是在第二个函数中,我得到位置为空(当我 console.log(location) 它打印正确的位置,在第二个打印时,第一个打印为空)似乎第二个函数没有等到第一个一个完成了。

这是一些代码:

从组件

    const location = useSelector(state => state.locationReducer.location);
    useEffect(()=> {
        (async () => {
            await getLocation();

            // here i'm using the location from the first function
            await getInfo(location);
        })()
    }, []);


    const getLocation = async() => {
        try {
            await dispatch(getLocation());
            console.log(location);
        } catch (err) {
            // TODO HANDLE ERROR;
            console.log('Err:', err);
        }
    }

在行动中

export const getLocation = locationName => {
    return async dispatch => {
        try {
            const location = **await** locationService.getLocation(locationName);
            **await** dispatch(setLocation(location));
        } catch (err) {
            throw err;
        };
    };
};

const setLocation = location => {
    return {
        type: types.SET_LOCATION,
        location
    };
};

在役


async function getLocation(locationName) {
    try {]
        return **await** axios.get(`${url}/${locationName}`);
    } catch (err) {
        throw err
    };
};

标签: javascriptreactjsreduxreact-redux

解决方案


在您的第一个函数运行后和第二个函数之前,选择器中的location值不会更新,因此您会在location变量中看到旧值。

您可能需要从减速器返回您的位置值:

export const getLocation = locationName => {
    return async dispatch => {
        try {
            const location = await locationService.getLocation(locationName);
            await dispatch(setLocation(location));

            return location;
        } catch (err) {
            throw err;
        };
    };
};

并使用您的返回位置useEffect

    useEffect(()=> {
        (async () => {
            const location = await getLocation();

            // here i'm using the location from the first function
            await getInfo(location);
        })()
    }, []);

或另一种可能性,以产生另一种效果,这取决于位置值:

    const location = useSelector(state => state.locationReducer.location);
    useEffect(()=> {
        getLocation();
    }, []);

    useEffect(()=> {
      if(location) {
        getInfo(location);
      }
    }, [location]);

这将在每次位置更改时运行,并且位置具有一定的价值。


推荐阅读