【问题标题】:Why are the props undefined for my React Component为什么我的 React 组件的道具未定义
【发布时间】:2018-02-19 05:50:27
【问题描述】:

我写了这个反应组件

class Row extends React.Component {
   constructor(props) {
      super(props);
      this.style = {
         display: "flex"
      }
   }
   render(){
      var rowcells = [];
      for(let i = 0; i < 7; i ++) {
         console.log("foo " + this.props.cells)                           
         rowcells.push(<Cell key={i} col ={i} row={this.props.row} cell={this.props.cells[i]} handleClick={this.props.handleClick}/>)
      }
      return (
         <div style = {this.style}>
            {rowcells}
         </div>
      )
   }
}

这个组件在我的应用程序中只被调用一次

for(let i = 6; i > 0; i--) {
  rows.push(<Row key={i} row={i} cells={this.props.cells[i]} handleClick={this.props.handleClick}/>)
}

所以你可以看到 props.cells 已经定义好了。但是当我的代码运行时,它在this.props.cells[I] 行失败,说它的未定义

https://codepen.io/knows_not_much/pen/dddNRZ?editors=1111

这是此处反应教程的示例

https://courses.edx.org/courses/course-v1:Microsoft+DEV281x+1T2018/courseware/404dd3a7096e46c5b4672e26e5a5b404/70c54b9d11ef4439a2996f9826ba6375/?child=last

示例和我的代码之间的唯一区别是我关闭了组件样式而不是 react 组件的函数样式。

【问题讨论】:

  • let i = 5 not let i = 6 在创建 Row 组件时的 for 循环中。您正在访问一个不存在的单元格数组项。

标签: reactjs


【解决方案1】:

您在创建 Row 组件(在您的 Board 组件内)时的 for loop 逻辑有一个错误:您正在访问一个不存在的单元格数组项。它应该是let i = 5,因为该数组有六个元素并且索引为 0 而不是let i = 6

几个console.log 语句帮助我解决了这个问题。

【讨论】:

    【解决方案2】:

    在下面的代码中,您没有遍历索引为 0 的数组的第一项,而且正如 @Govind 建议的那样,i=6 必须是 i=5,所以这样:

    for(let i = 6; i > 0; i--) {
      rows.push(<Row key={i} row={i} cells={this.props.cells[i]} handleClick={this.props.handleClick}/>)
    }
    

    必须是这样的:

    for(let i = 5; i >= 0; i--) { //notice the greater or equal sign (>=)
      rows.push(<Row key={i} row={i} cells={this.props.cells[i]} handleClick={this.props.handleClick}/>)
    }
    

    See it in action

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 1970-01-01
      • 2021-06-06
      • 2018-11-04
      • 2021-07-01
      • 2018-10-27
      • 2020-01-06
      • 2017-02-19
      • 2018-06-11
      相关资源
      最近更新 更多