我试图useState
在 API 调用之后设置一个变量,但它不起作用。通过 reactotron 调试,他进行 API 调用,但他没有设置变量。
export default function Forecast({ navigation }) {
const [cityData, setCityData] = useState([]);
const idNavigation = navigation.state.params.cityData.woeid;
async function loadCityData(cityID) {
const response = await api.get(`${cityID}`);
setCityData([response]);
console.tron.log(cityData);
}
useEffect(() => {
if (idNavigation) {
loadCityData(idNavigation);
}
return () => {};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [idNavigation]);
return <Text>Forecast Weather</Text>;
}
Forecast.propTypes = {
navigation: PropTypes.shape({
state: PropTypes.object,
}).isRequired,
};
在 React 中设置状态在大多数情况下是异步的,如果您尝试立即使用 console.log 对状态的更改可能不可见。使用钩子执行此操作的推荐方法是检查 中的更新状态useEffect
:
async function loadCityData(cityID) {
const response = await api.get(`${cityID}`);
setCityData([response]);
}
// Track cityData and log the changes to it
useEffect(() => {
console.log(cityData);
}, [cityData]);
// Rest of the code
// ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句