简体   繁体   English

为什么我的React组件的props未定义

[英]Why are the props undefined for my React Component

I wrote this react component 我写了这个React组件

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>
      )
   }
}

this component is called only once in my application like 该组件在我的应用程序中仅被调用一次,例如

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

So you can see that the props.cells is defined. 因此,您可以看到props.cells已定义。 but when my code runs it fails by at the line this.props.cells[I] by saying its undefined 但是,当我的代码运行时,它在this.props.cells[I]行中失败,并说未定义

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

This is a example from the react tutorial here 这是来自React教程的示例

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

The only difference between the sample and my code is that I am closing the component style rather than function style for react components. 该示例与我的代码之间的唯一区别是,我将关闭组件样式而不是React组件的函数样式。

Your for loop logic when creating Row components (inside your Board Component) has an error: You're accessing a item of the cells array which does not exist. 创建“行”组件(在“董事会组件”内部)时,您的for loop逻辑有错误:您正在访问单元格数组中不存在的项。 It should be let i = 5 since the array has six elements and is 0 indexed not let i = 6 . 应该let i = 5因为数组有六个元素并且索引为0而不let i = 6

Couple of console.log statements helped me to the issue. 几个console.log语句帮助我解决了这个问题。

In the code below you're not iterating over the first item of the array which is index 0, and also as @Govind suggested the i=6 must be i=5 , so this: 在下面的代码中,您没有迭代数组的第一项(索引为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}/>)
}

must be this: 必须是这样的:

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 实际观看

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

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