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 打印预期值,但第二个 console.log 给出未定义的值,就好像异步函数从未对变量检查产生任何影响一样。 我需要来自
getData(props.path)
的检查值,以便将其显示在 <Text>
组件中。
有什么想法吗?
将其置于状态。
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>
);
}
小建议:此外,您可以创建自己的钩子来在不同的文件中计算它并在任何地方使用它。类似的东西
const check = useCheck();
export function useCheck() {
const [check, setCheck] = useState(null);
useEffect(() => {
(async () => {
const data = await getData(props.path);
setCheck(data);
})();
}, []);
return check;
}