开发者问题收集

未捕获的类型错误:无法读取未定义的属性(读取“0”),求和 useState 数组

2022-12-10
483
const [lnames, setlNames] = React.useState();
    const [lnums, setlNums] = React.useState();
    
    React.useEffect(() => {
      axios.get("http://localhost:7001/lunch").then(response => {
        let arr1 = [];
        let arr2 = [];
    
        response.data.forEach(c => {
          arr1.push(c.table_id);
          arr2.push(c.table_num_count);
        });
    
        setlNames(arr1);
        setlNums(arr2);
      });
    }, []);
    
    const [dnums, setdNums] = React.useState();
    
    React.useEffect(() => {
      axios.get("http://localhost:7001/dinner").then(response => {
        let arr1 = [];
        response.data.forEach(c => {
          arr1.push(c.table_num_count);
        });
        setdNums(arr1);
      });
    }, []);
    
    const [bnums, setbNums] = React.useState();
    
    React.useEffect(() => {
      axios.get("http://localhost:7001/breakfast").then(response => {
        let arr1 = [];
        response.data.forEach(c => {
          arr1.push(c.table_num_count);
        });
        setbNums(arr1);
      });
    }, []);
    
    const customer_count_breakfast = bnums;
    const customer_count_lunch = lnums;
    const customer_count_dinner = dnums;
    
    let sumArray = []
    
if (lnums & lnums.length > 0) {
  //sumArray = lnums.map((l, i) => l + bnums[i] + dnums[i]);
  for (let i = 0; i < lnums.length; i++) {
    sumArray[i] = bnums[i] + lnums[i] + dnums[i];
  }
}

// IF COMMENT ABOVE AND UNCOMMENT HERE THE ERROR IS GONE BUT sumArray is not computed
// if (lnums && lnums[0]) {
//   //sumArray = lnums.map((l, i) => l + bnums[i] + dnums[i]);
//   for (let i = 0; i < lnums.length; i++) {
//     sumArray[i] = bnums[i] + lnums[i] + dnums[i];
//   }
// }

您好,上面的代码在 if 循环条件下给出了以下错误:未捕获类型错误:无法读取未定义的属性(读取“0”)。我想我知道为什么会显示此错误。这表明我正在尝试访问未定义的变量的属性或索引,这很可能是由于 useEffect 造成的,当我调用 if 条件时,值尚未设置,因此它是未定义的,因此没有长度。当我尝试注释第一个 if 条件并取消注释第二个 if 条件时,没有出现任何错误,但求和不起作用,它返回一个空数组。

在这种情况下,我如何才能对 .useState() 变量的值求和?

2个回答

您需要研究 react lifecycle 和 useMemo。

阅读有关 lifecycle 的信息: https://www.w3schools.com/react/react_lifecycle.asp

阅读有关 useMemo 的信息: https://www.w3schools.com/react/react_usememo.asp

这里有一个简单的例子,useEffect 将数字放入一个数组中,useMemo 依赖于这些数组并将所有数字相加。

import { useEffect, useState, useMemo } from "react";

export default function App() {
  const [arr1, setArr1] = useState([]);
  const [arr2, setArr2] = useState([]);

  // called everytime arr1 or arr2 changes. Which causes react to rerender.
  // first run sum = 0
  const sum = useMemo(() => {
    let res = 0;

    if (arr1.length && arr2.length) {
      for (let i = 0; i < arr1.length; i++) {
        res += arr1[i] + arr2[i];
      }
    }

    return res;
  }, [arr1, arr2]);

  // called once, updated setArr1 causing sum to be called
  useEffect(() => {
    setArr1([1,2,3]);
  }, []);

  // called once, updated setArr2 causing sum to be called
  useEffect(() => {
   setArr2([4,5,6]);
  }, []);

 return (
  <div>
   <p> sum: {sum} </p>
  </div>
 );

}

本质上,在您的代码中,您在 useEffect 完成设置之前调用数组值。

enak-nalla
2022-12-10

我通过添加 try-catch 语句解决了该问题,但不确定是否可行

try {
  for (let i = 0; i < lnums.length; i++) {
    sumArray[i] = bnums[i] + lnums[i] + dnums[i];
  }
  console.log("Statement was successful");
} catch (error) {
  
}
Cindy Burker
2022-12-10