我正在尝试使用setState通过阿波罗客户端的OnCompleted函数来设置useQuery中的数据,但是它似乎没有设置数据,我正在努力找出原因。
另外,一旦设置了setState,我的表映射是否会相应地更新?
handleSubmit函数中的console.log始终为空,并且没有任何映射。但是如果我做data.horses控制台日志,它就在那里。
下面是我的代码:
import { useQuery, gql } from "@apollo/client";
import { useState } from "react";
const DataTable = () => {
const GET_HORSES = gql`
query{
horses{
horseCode
horseName
foalingYear
gender
trainer{
trainerCode
}
}
}`;
const [horses, setHorses] = useState([]);
const { data, loading, error} = useQuery(GET_HORSES, {
OnCompleted: (data) => setHorses(data.horses)
});
if (loading) { return "Loading..." };
if (error) { return "Error loading data!"};
if (!data) { return "No data available!"};
const handleSubmit = () => {
var ddSearch = document.getElementById("ddSearch");
var ddSearchVal = ddSearch.value;
if(ddSearchVal === "HorseCode") {
}
console.log(horses);
}
return (
<div className="flex-column">
<div className="Data-search">
<strong>Searching</strong>
<br/>
<select id="ddSearch" >
<option value="HorseCode">Horse Code</option>
<option value="TrainerCode">Trainer Code</option>
<option value="HorseName">Horse Name</option>
</select>
<br/>
<input type="txtSearch" id="search" style={{width: 94}}/>
<br/><br/>
<strong>Foaling Year</strong>
<br />
From:<br/>
<input type="number" id="foalingYearMin" min="2000" max="2010" style={{width: 94}} /><br/>
To:<br/>
<input type="number" id="foalingYearMax" min="2000" max="2010" style={{width: 94}} />
<br/><br/>
<strong>Gender:</strong><br/>
<select id="ddGender" style={{width: 94}}>
<option value="g">g</option>
<option value="f">f</option>
<option value="c">c</option>
</select>
<br/><br/>
<button type="button" style={{width: 94}} onClick={() => handleSubmit()}>Search</button>
<br/>
<button type="button" style={{width: 94}}>Reset</button>
</div>
<table className="Data-table">
<thead>
<tr>
<th>Horse Code</th>
<th>Horse Name</th>
<th>Foaling Year</th>
<th>Gender</th>
<th>Trainer Code</th>
</tr>
</thead>
<tbody>
{horses.map((horse) => (
<tr key={horse.horseCode}>
<td>{horse.horseCode}</td>
<td>{horse.horseName}</td>
<td>{horse.foalingYear}</td>
<td>{horse.gender}</td>
<td>{horse.trainer.trainerCode}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default DataTable;我还将使用文本搜索输入对此数组进行过滤
发布于 2021-08-06 15:12:17
这是onCompleted而不是OnCompleted -这就是为什么即使data更新了结果,你的状态也保持不变。
一旦React提交了由setHorses调用调度的更改,表就应该立即更新(为了简单起见,只要调用setHorses,我们就可以看到)。
出于过滤的目的(在评论中提到),实际上并不需要在本地状态下凝视数据。您可以在将结果映射到React组件之前使用filter过滤结果,或者使用useMemo钩子来防止不必要的迭代。
https://stackoverflow.com/questions/68683277
复制相似问题