useState对象数组 [英] useState Array of Objects
问题描述
我有一个搜索框,可以复制和粘贴excel中的列.我解析输入并生成条目数组.
I have a search box that I can copy and paste a column from excel. I parse the input and generate an array of the entries.
然后,我正在映射条目,并为每个项目调用一个自定义钩子,以从我的graphql
端点中获取一些数据.
I am then mapping over the entries and calling a custom hook with each item to fetch some data from my graphql
endpoint.
例如:
在搜索框中提供了3个条目:
3 entries are provided from the search box:
["D38999/26", "LJT06RE25-61PA", "D38999/46FJ61AA"]
fetchData
函数一次接收这些项之一作为查询参数.当前,此过程将返回3个单独的对象,例如:
The fetchData
function receives one of these items at a time as the query parameter. Currently, this process would return 3 separate objects as such:
{query: "D38999/26", cables: Array(35)}
{query: "LJT06RE25-61PA", cables: Array(1)}
{query: "D38999/46FJ61AA", cables: Array(1)}
如何设置反应挂钩,以允许我将每个对象作为对象数组附加到result
状态?
How do I set up a react hook to allow me to append each object into the result
State as an array of objects?
我的最终目标将是这样的对象数组:
My end goal would be an array of objects like this:
[
{query: "D38999/26", cables: Array(35)},
{query: "LJT06RE25-61PA", cables: Array(1)},
{query: "D38999/46FJ61AA", cables: Array(1)}
]
这是我当前用于解析API端点的自定义钩子
This is my current custom hook to resolve my API endpoint
const useCableMatch = () => {
const [result, setResult] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const client = useApolloClient();
const fetchData = async query => {
setIsError(false);
setIsLoading(true);
try {
const { data } = await client.query({
query: GET_VALID_CABLE,
variables: { pn: `%${query}%` },
});
const response = { query, ...data };
console.log('response:', response);
setResult(response);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
return [{ result, isLoading, isError }, fetchData];
};
当前setResult
设置为仅从响应中返回单个对象.我想返回一个数组,其中每个生成的对象都附加到现有的对象数组中.
Currently setResult
is set up to only return a single object from response. I would like to return an array with each object generated appended to the existing array of objects.
推荐答案
假定可以将response
直接添加到result
数组中,则可以:
Assuming that response
can be added directly to result
array, you can:
setResult(result => [...result, response]);
这将使用 查看全文