[英]Not able to see output of state using react hooks (useState) after fetch
[英]Not able to change React state using useState
我在使用 React Native 和 Expo 获取用户位置时进行了条件渲染。 单击按钮以显示微调器后,我正在更改状态,但是由于某种原因,我的状态变量始终为 false。 我理解 useEffect 钩子,但是我认为我不需要在任何特定的生命周期中更改变量。 这是正确的推理吗? 起初我认为这是由于函数的异步性质,但似乎不太可能。
状态初始化
const [loading, toggleLoading] = useState(false);
onClick 的代码
{props.location === null ? (
<Button onPress={getLocationAsync} mode="contained">
Get Location
</Button>
) : loading === true ? (
<Button mode="contained">
<ActivityIndicator />
</Button>
) : (
<Button mode="outlined">Received</Button>
)}
getLocationAsync 的代码
const getLocationAsync = async () => {
toggleLoading(true);
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") { }
let location = await Location.getCurrentPositionAsync();
toggleLoading(false);
};
在任何地方记录状态总是产生错误的加载。 在这种情况下,我真的需要像 useEffect 这样的东西吗?
在 React 中设置状态是异步的! 这就是您的日志显示false
的原因。
const onPress = () => toggleLoading(true)
useEffect(() => {
const getLocationAsync = async () => {
// your actions here
toggleLoading(false)
}
if (loading) getLocationAsync()
}, [loading])
// in your render
<Button {...{ onPress}} mode="contained">Get Location</Button>
如果您这样做,您就 100% 确定getLocationAsync()
代码仅在loading === true
时执行!
你确定它不起作用? State
在作出反应是异步太让你console.log()
可能会不准确。
我用你的代码创建了简单的例子,它运行良好。 唯一可能不同的是您的三元条件。 您看不到“正在加载”,因为您的第一个条件是location === null
,即使在加载时也是null
。 我刚刚修改了您的第一个条件,如下所示: location === null && loading !== true
并且工作正常。
你能试一下吗
onPress={() => {
toggleLoading(true);
getLocationAsync();
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.