【发布时间】: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) 的检查值,以便在<Text> 组件中显示它。
有什么想法吗?
【问题讨论】:
-
将数据放入状态并更新状态。
标签: javascript android react-native asynchronous asyncstorage