正如我在標題中提到的,當我在我的 Picker 中選擇一個新值時,控制臺顯示一切正常,但我的提取不想用新的 selectedValue 更新它。
如果我手動將引數傳遞給 useState,則 fetch 會更新它,但我不知道如何強制它自動更新。這里的代碼:
export default function Bien() {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
// problem here
const [selectedValue, setSelectedValue] = useState('tous');
const fetchValue = 'https://www.api.lereseaufoncier.fr/stock?category=' selectedValue
// the console.log works and show the new selectedValue
console.log(fetchValue)
//but here, the query don't refresh
//if I pass 'maisons' or 'appartements' in the new state manually, it works
useEffect(() => {
fetch(fetchValue)
.then((response) => response.json())
.then((json) => setData(json ? json.table : []))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
const postLayoutComponent = data.map(table => <AEPostLayout key={table.ID} table={table}/> )
return (
<SafeAreaView>
<View style={{justifyContent: 'center', alignItems: 'center', width:'100%'}}>
<Spacer taille={30} />
<Picker
selectedValue={selectedValue}
style={{ height: 50, width: 195 }}
onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}
>
<Picker.Item label="Tous Nos Biens" value="tous" />
<Picker.Item label="Nos Maisons" value="maisons" />
<Picker.Item label="Nos Terrains à batir" value="terrains à batir" />
<Picker.Item label="Nos Appartements" value="appartements" />
</Picker>
<Spacer taille={10} />
</View>
<ScrollView>
{postLayoutComponent}
</ScrollView>
</SafeAreaView>
);
}
我希望有一個人可以幫助我。謝謝
uj5u.com熱心網友回復:
請嘗試以下操作:
useEffect(() => {
const fetchValue = 'https://www.api.lereseaufoncier.fr/stock?category=' selectedValue
fetch(fetchValue)
.then((response) => response.json())
.then((json) => setData(json ? json.table : []))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, [selectedValue]);
這樣,添加依賴項useEffect告訴鉤子每次selectedValue發生變化時,組件都應該重新渲染并重新獲取資料。
uj5u.com熱心網友回復:
謝謝你一切正常。也感謝您提供指向檔案的鏈接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399768.html
標籤:反应原生
