【问题标题】:How to get value from async function in react-native?如何从 react-native 中的异步函数中获取价值?
【发布时间】:2020-08-27 04:11:00
【问题描述】:
function CategoryCard (props) {

    const [done, setDone] = React.useState(null);
    let check;

    React.useEffect(() => {
        async function checkData() {
            check = await getData(props.path);
            // prints CORRECTLY
            console.log(check);
        }
        checkData();
    //prints INCORRECTLY
        console.log(check);
        setDone(true);
    }, []);

    return (

        <View>
        {done ? (
            <Text>{check}</Text>
        ):(
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#99ff99" />
            </View>
        )}
        </View>
    );
}

如何从异步函数中获取值到 react-native 中的常规函数​​中? 在上面的代码中,第一个 console.log 打印了预期值,但第二个给出了 undefined,就好像 async 函数对变量检查没有任何影响一样。 我需要来自getData(props.path) 的检查值,以便在&lt;Text&gt; 组件中显示它。

有什么想法吗?

【问题讨论】:

  • 将数据放入状态并更新状态。

标签: javascript android react-native asynchronous asyncstorage


【解决方案1】:

把它放在状态。

function CategoryCard (props) {

    const [check, setCheck] = React.useState(null);

    React.useEffect(() => {
        async function checkData() {
            const data = await getData(props.path);
            setCheck(data);
        }
        checkData();

    }, []);

    return (

        <View>
        {check ? (
            <Text>{check}</Text>
        ):(
            <View style={[styles.container, styles.horizontal]}>
                <ActivityIndicator size="large" color="#99ff99" />
            </View>
        )}
        </View>
    );
}

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2016-05-22
    • 2021-02-13
    相关资源
    最近更新 更多