简体   繁体   English

React TypeError:无法读取未定义的属性“0”

[英]React TypeError: Cannot read property '0' of undefined

I am writing a function to calculate the individual column total of 12 rows and create a new array of the total values of the same size but i keep getting the error我正在编写一个函数来计算总共 12 行的单个列,并创建一个具有相同大小的总值的新数组,但我不断收到错误消息

TypeError: Cannot read property '0' of undefined how do i resove it类型错误:无法读取未定义的属性“0”我如何解决它

new_matrix of dimension [6][12] is pre calculated and then passed into the colTotaler function as also the matrix input is obtained through a matrix input form维度 [6][12] 的 new_matrix 是预先计算的,然后传递给 colTotaler 函数,同时矩阵输入也是通过矩阵输入形式获得的

colToataler(new_matrix); colToataler(新矩阵);

let columns = [0,0,0,0,0,0,0,0,0,0,0,0];

const[col,setCol] = useState(columns);

const colTotaler = (new_matrix) => {
   let i = 0,
     j = 0;

   for (i = 0; i < new_matrix[0].length; i++) {
     for (j = 0; j < new_matrix.length; j++) {
       columns[i] += new_matrix[i][j];
     }
   }

   setCol(columns);
 };

The way you choose to calculate colTotaler isn't good enought.您选择计算 colTotaler 的方式还不够好。 I would suggest you to do this in functional way, using map , reduce and reactivity of React:我建议您以功能方式执行此操作,使用 React 的mapreduce和反应性:

const [matrix, setMatrix] = useState(defaultMatrix)

const colTotaler = matrix.map((column) => {
  return column.reduce((colTotal, element) => colTotal+ element, 0)
})

Now, every time when setMatrix will be called, component will rerendered and colTotaler will be recalculated.现在,每当时间setMatrix将被调用,组件将重新描绘和colTotaler将重新计算。

If you pass new_matrix from state, the initial value of the state could be undefined.如果从 state 传递new_matrix ,则 state 的初始值可能未定义。 To fix that you can add if statement to check it state is initialized:要解决这个问题,您可以添加 if 语句来检查它的状态是否已初始化:

let comumns = [0,0,0,0,0,0,0,0,0,0,0,0];

const[col,setCol] = useState(columns);

const colTotaler = (new_matrix) => {
   if (new_matrix) {
     let i = 0,
       j = 0;

     for (i = 0; i < new_matrix[0].length; i++) {
       for (j = 0; j < new_matrix.length; j++) {
         columns[i] += new_matrix[i][j];
       }
     }

     setCol(columns);
   }
 };

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

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