正如我在标题中提到的,当我在Picker中选择一个新值时,控制台会显示一切正常,但我的fetch不想用新的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 à bâtir" value="terrains à bâtir" />
<Picker.Item label="Nos Appartements" value="appartements" />
</Picker>
<Spacer taille={10} />
</View>
<ScrollView>
{postLayoutComponent}
</ScrollView>
</SafeAreaView>
);
}
我希望有人能帮助我。谢谢
尝试以下操作:
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
添加依赖项告诉hook,每次selectedValue
更改时,组件都应该重新提交和重新匹配数据。
感谢您所做的一切。同时也感谢您提供的文档链接。