在我的 react native 功能組件中,狀態會更新,但是當我想在函式中使用此狀態時(例如,將資料發送到 API),它僅使用初始狀態。
imports...
const Component = ({ navigation }) => {
const [ids, setIds] = useState([1,2]);
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => <HeaderRight
onPress={() =>
console.log(ids); // this logs initial state, i.e, [1,2]
updateIdsToServerViaAPI(); // and therefore I'm unable to update ids using this method
}
/>
});
}, [navigation]);
const updateIdsToServerViaAPI = async () => {} // function that takes updated ids from state.
const onPress = async () => {
const newIds = [...ids, 3, 4];
setIds(newIds);
}
const onPressInsideComp = () => {
console.log(ids);
// here updated ids gets logged.
}
return (
<View>
<Button onPress={onPress} />
{ids.map(id => (
<Text key={id}>{id}</Text> {\* Here you will see 4 texts after pressing button, that means state gets updated*\}
)}
<Button onPress={onPressInsideComp} />
</View>
);
}
似乎這個問題只有在內部呼叫函式時才會發生,useLayoutEffect或者useEffect當我onPressInsideComp從組件內部的按鈕呼叫時,它會正確記錄!
我嚴重卡在這個奇怪的問題上!
uj5u.com熱心網友回復:
您只在包裝器navigation的依賴陣列中提供了 prop ,因此如果狀態更改,則不會重新創建該函式。useLayoutEffectids
您可能想要創建一個不同的函式,包裝在 a中,該函式useCallback將ids狀態作為依賴項并在您的useLayoutEffect.
const doSomething = useCallback(() => {
console.log(ids);
updateIdsToServerViaAPI();
}, [ids])
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => <HeaderRight
onPress={() =>
doSomething(ids)
}
/>
});
}, [navigation, ids, doSomething]);
uj5u.com熱心網友回復:
在您的代碼中,console.log(ids)是在函式定義時解決的,而不是在執行時解決的,因此它采用您在定義中獲得的參考const [ids, setIds} = useState([1,2])。
也許只是嘗試使用狀態函式而不是使用之前定義的變數來獲取您的 id:
const [ids, setIds] = useState([1,2]);
const get_ids = () => this.state.ids;
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => <HeaderRight
onPress={() =>
console.log(get_ids());
updateIdsToServerViaAPI();
}
/>
});
}, [navigation]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433651.html
標籤:javascript 反应 反应式 反应钩子
下一篇:TS我如何將此函式寫入箭頭函式?
