reactjs 未捕获的类型错误:无法读取undefined的属性(阅读“0”),正在对useState数组求和

piwo6bdm  于 2022-12-12  发布在  React
关注(0)|答案(2)|浏览(149)
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];
//   }
// }

下面是一个例子,在上面的代码中,我们可以看到下面的代码:未捕获的类型错误:无法读取未定义的属性(阅读'0')。我想我知道为什么会显示错误。它表示我正在尝试访问未定义的变量的属性或索引,这很可能是由于useEffect,当我调用if条件时,值还没有设置,所以它是未定义的,因此没有长度。当我尝试注解第一个if条件并取消注解第二个if条件时,我没有得到更多的错误,但是求和不起作用,它返回一个空数组。
在这种情况下,如何对.useState()变量的值求和?

bjp0bcyl

bjp0bcyl1#

我通过添加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) {
  
}
s5a0g9ez

s5a0g9ez2#

您需要查看React生命周期和useMemo。
阅读生命周期: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完成设置数组值之前调用数组。

相关问题