当一个数字作为它的道具传递时,为什么我的Reaction组件键返回未定义的?

qmelpv7a  于 2022-09-21  发布在  React
关注(0)|答案(1)|浏览(105)

我的目标是创建一个组件网格,并保存该网格上每个组件的状态数据。为此,我尝试使用与网格上的每个组件相对应的对象数组,该数组的初始化方式如下:

let count = 0;
for(let i = 0; i < 15; i++){
    for(let j = 0; j < 30; j++){
      count++;
      let x = 0;
      if(i % 2 !== 0){
        x = j * WIDTH_OF_CELL + OFFSET_X;
      } else {
        x = j * WIDTH_OF_CELL + OFFSET_X + 24;
      }
      const y = i * HEIGHT_OF_CELL + OFFSET_Y;

      let cell = {
        y: y,
        x: x,
        centerX: x + 25,
        centerY: y + 25,
        state: 0,
        key: count
      }
      cellsGrid.push(cell);
    }
  }

然后,为了实际呈现组件,迭代中间组件将cellsGrid数组作为道具,并将每个对象Map到一个单元组件:

return (
    <div>
      {cellsGrid.map((item) => 
        <Cell 
        key={item.key} 
        postitX={item.x} 
        postitY={item.y} 
        edit={edit} 
        state={item.state} 
        handleClick={handleClick}>
        </Cell>
      )}
    </div>
)

state属性表示单元格是打开还是关闭,它被初始化为0,当单元格被单击时,它应该更新为1,为此,handleClick函数作为道具向下传递给单元组件:

const handleClick = (event, state, key, callback) => {
    callback();
    let index = cellsGrid.findIndex(cell => cell.key === key);
    cellsGrid[index].state = state;
  };

在单元格组件handleClick内部,传递基于其内部状态、刚被单击的单元格的键以及其状态的值,因为每个单元格组件都是使用cellsGrid数组创建的,所以单元格的键应该对应于生成它的数组对象的键:

onClick={event => handleClick(event, currentState.state, key, nextState)}

但当单击单元格时,控制台会抛出一个错误:

未捕获的TypeError:无法设置未定义的属性(设置“”State“”)

我尝试在handleClick函数中记录keyindex的值:

const handleClick = (event, state, key, callback) => {
    callback();
    let index = cellsGrid.findIndex(cell => cell.key === key);
    //cellsGrid[index].state = state;
    console.log(key);
    console.log(index);
  };

输出:

undefined

-1

我不明白为什么key是未定义的,它应该是与cellsGrid数组中的对象相同的键,这样我就可以找到该对象并将其更新为state。抱歉,如果代码看起来粗糙,我是新手React和脚本,任何帮助都将不胜感激。

nimxete2

nimxete21#

不要将钥匙用作道具。钥匙不是作为道具传递的。键由Reaction内部使用,以帮助优化节点的呈现,您可以将索引作为类似的道具传递

<MyComponent index={item.key}

props.index would have the value.

相关问题