我正在開發基于 React JS 的 UI 并面臨資料問題。
- 我從 API 獲取資料并使用 useState 掛鉤將其存盤在初始值中。
- 然后我使用 useEffect 通過 setLists() 將它存盤在“串列”中
const [lists, setLists] = useState([]);
useEffect(()=>{
const url = "https://domain/api/all";
fetch(url).then(response => response.json()).then(response=> {
setLists(response.json.list);
});
- 現在我可以使用地圖在表中輸入資料
- Lists 是一個陣列物件,其中有多個值,我想根據年齡和國家/地區過濾表格
let [ageList, setAgeList] = useState([]);
let [countryList, setcoutryList] = useState([]);
useEffect(()=>{
var newList = lists.filter(e=> e.age === age);
setList(newList)
},[age])
useEffect(()=>{
setlist(lists.filter(e=> e.country === country))
},[country])
使用這種方法,第一次嘗試過濾器在年齡和國家/地區都可以正常作業,但是當我更改年齡或國家/地區的過濾器值時,我得到空陣列,這是預期的,因為新串列變數已輸入最后過濾的國家/地區/年齡
我怎樣才能克服這個?
uj5u.com熱心網友回復:
正如您所注意到的,當您用過濾后的狀態覆寫之前的狀態時,您將永遠失去之前的狀態。此處的解決方案是保留 的初始值lists并為過濾串列創建一個新變數。像這樣的東西:
const [lists, setLists] = useState([]);
const [ageFilter, setAgeFilter] = useState("");
const [countryFilter, setcountryFilter] = useState("");
const url = "https://domain/api/all";
fetch(url)
.then(response => response.json())
.then(response=> {
setLists(response.json.list);
});
let filteredByCountryAndAge = listfilter((listItem) => {
return (listItem.country === countryFilter && listItem.age === ageFilter);
});
(或者您正在過濾它)。
重點是,lists在設定整個串列后不要更改 的值。過濾時,將過濾所依據的標準分配給狀態變數,但將過濾后的資料分配給變數,而不是狀態變數。
uj5u.com熱心網友回復:
您是否可以控制獲取的資料?如果是這樣,顯而易見的解決方案是更改資料模型服務器端。
如果沒有,我建議將初始回應存盤在來自useRef.
編輯
const [lists, setLists] = useState([]);
const cache = useRef([]);
useEffect(()=>{
const url = "https://domain/api/all";
fetch(url).then(response => response.json()).then(response=> {
cache.current = response.json.list;
setLists(response.json.list);
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365177.html
標籤:javascript 反应
