1 回答

TA貢獻1797條經驗 獲得超4個贊
您正在使用 forEach 并將返回的值分配給變量,但不返回任何內容。您應該改用地圖forEach
let municipiosNames = municipiosFromContext.map((municipio) => {
return `label: ${municipio.NOMBRE}`;
});
根據您的評論:
您的數據是異步加載的,因此在首次呈現時將不可用,并且由于功能組件依賴于閉包,因此 onSearchChange 函數在創建時從閉包中獲取值,即使您其中有一個 setTimeout,更新的值也不會反映
這里的解決方案是添加為依賴項以使用效果municipiosFromContext
const onSearchChange = useCallback((searchValue) => {
setLoading(true);
setOptions([]);
clearTimeout(searchTimeout);
// eslint-disable-next-line react-hooks/exhaustive-deps
searchTimeout = setTimeout(() => {
// Simulate a remotely-executed search.
setLoading(false);
setOptions(
municipiosNames.filter((option) =>
option.label.toLowerCase().includes(searchValue.toLowerCase())
)
);
}, 1200);
}, [municipiosFromContext]);
useEffect(() => {
// Simulate initial load.
onSearchChange("");
}, [onSearchChange]);
添加回答
舉報