简体   繁体   English

useState 对象数组

[英]useState Array of Objects

I have a search box that I can copy and paste a column from excel.我有一个搜索框,可以从 Excel 中复制和粘贴一列。 I parse the input and generate an array of the entries.我解析输入并生成一个条目数组。

I am then mapping over the entries and calling a custom hook with each item to fetch some data from my graphql endpoint.然后我映射条目并调用每个项目的自定义钩子以从我的graphql端点获取一些数据。

For example:例如:

3 entries are provided from the search box:搜索框中提供了 3 个条目:

["D38999/26", "LJT06RE25-61PA", "D38999/46FJ61AA"]

The fetchData function receives one of these items at a time as the query parameter. fetchData函数一次接收这些项目之一作为查询参数。 Currently, this process would return 3 separate objects as such:目前,此过程将返回 3 个单独的对象,如下所示:

{query: "D38999/26", cables: Array(35)}
{query: "LJT06RE25-61PA", cables: Array(1)}
{query: "D38999/46FJ61AA", cables: Array(1)}

How do I set up a react hook to allow me to append each object into the result State as an array of objects?如何设置反应钩子以允许我将每个对象作为对象数组附加到result状态中?

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)}
]

This is my current custom hook to resolve my API endpoint这是我当前用于解析 API 端点的自定义钩子

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];
};

Currently setResult is set up to only return a single object from response.当前setResult设置为仅从响应中返回单个对象。 I would like to return an array with each object generated appended to the existing array of objects.我想返回一个数组,其中生成的每个对象都附加到现有的对象数组中。

Assuming that response can be added directly to result array, you can:假设可以将response直接添加到result数组中,您可以:

setResult(result => [...result, response]);

This will append the new response from the previous result state and by using array spread operator .这将通过使用array spread operator附加来自先前result状态的新response

You could just pass the entire array into the hook and return the result as an array.您可以将整个数组传递给钩子并将结果作为数组返回。 You should also use useEffect for async logic.您还应该将useEffect用于异步逻辑。 I rewrote your code to process all 3 fields at once:我重写了您的代码以一次处理所有 3 个字段:

const useCableMatch = (searchInput) => {
  const [result, setResult] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const client = useApolloClient();

  useEffect((searchInput) => {
     setIsError(false);
     setIsLoading(true);
     let response
     for(let field of searchInput){
        try {
           const { data } = await client.query({
              query: GET_VALID_CABLE,
              variables: { pn: `%${field}%` },
           });

           response = { ...data };
         } catch (error) {
             setIsError(true);
         }
     }
     setResult(current => {query, ...current, ...response);
     setIsLoading(false);
   };
  }, [searchInput])

  return [{ result, isLoading, isError }];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM