我有 react 在创建时提供的默认App
函数。
我正在尝试为初始显示获取一些数据:
const [people, setPeople] = useState([]);
useEffect(() => {
fetch("http://localhost:8080/restApiTest").then(res => {
return res.json();
}).then(data => {
let array_people = data.map((p) => {
return p.firstName + ' ' + p.lastName;
});
setPeople(array_people);
});
}, []);
问题是此数据仅在我重新渲染子组件时呈现。如何加载初始数据?
我试图遵循 React Effect Hooks 和 React State Hooks
编辑:添加函数的其余部分
function App() {
// const people = ["Arnaud", "Etienne", "Riccardo", "Ed", "Jose"];
const [people, setPeople] = useState([]);
const [filtered, setFiltered] = useState(people);
useEffect(() => {
fetch("http://localhost:8080/restApiTest").then(res => {
return res.json();
}).then(data => {
let array_people = data.map((p) => {
return p.firstName + ' ' + p.lastName;
});
setPeople(array_people);
});
}, []);
console.log(people);
const filterPeople = (data) => {
let filters = people.filter((name) => {
return name.toLowerCase().indexOf(data.toLowerCase()) !== -1;
});
setFiltered(filters);
};
return (
<div className="App">
<div>
<SearchBar onEnter={filterPeople}/>
<SortableList people={filtered}/>
</div>
</div>
);
}
问题是,当useImpact 的回调使用获取的数据设置people
状态时,filtered
状态仍然保持不变,即[]
而不是按照新的people
状态。只是在初始挂载上,您的filtered
状态将设置为people
状态,而不是像您期望的那样在每次后续重新渲染时。要使用获取的数据更新filtered
状态,您必须在 useEffect 中显式调用setFiltered
函数,如下所示:
useEffect(() => {
fetch("http://localhost:8080/restApiTest")
.then(res => res.json())
.then(data => {
let array_people = data.map((p) => {
return p.firstName + ' ' + p.lastName;
});
setPeople(array_people);
setFiltered(array_people)
});
}, []);