在jsx中读取数组值

时间:2019-01-20 12:52:26

标签: arrays reactjs

在我的Next.JS应用程序中,我正在将数组作为道具传递给OrderViewer组件,但是当我尝试读取JSX内部的passs数组的项目时,抛出了以下错误。 / p>

  

未处理的拒绝(TypeError):无法读取null的属性“ 0”

getOrderData = ID => {
  if (ID !== null){
    this.prt.style.display = "block";
    console.log(ID) //This works well.but it doesn't work inside JSX.
    console.log(`type = ${typeof(ID)}`)
  }
}

render(){
  return(
    <div ref={ref => this.prt = ref} onLoad= {this.getOrderData(this.props.orderId)} style={{display: "none"}}>
      <div id="OOP" className="row">
        <div className={"row"}>
          <div className="col-md-1">{this.props.orderId}</div>
          <div className="col-md-10"></div>
          <div className="col-md-1"></div>
        </div>
        <div></div>
      </div>
    </div>)
}

1 个答案:

答案 0 :(得分:1)

在您的代码中,Orders组件的state为:

constructor(props){
  super(props);
  this.state = {
    orderId: null
  }

您将Orders组件状态作为道具传递给OrderViewer组件

<OrderViewer orderId={this.state.orderId}/> 

内部OrderViewer组件

 // Remember "this.props.orderId" is null 
        getOrderData = ID => {  
            // ID is equal to null so this block is not executed 
            if (ID !== null){
                this.prt.style.display = "block";
                console.log(ID[0]) 
            }
        }

        render(){
            return(
                <div ref={ref => this.prt = ref} onLoad= 
        {this.getOrderData(this.props.orderId)} style={{display: "none"}}>
                    <div id="OOP" className="row">
                       <div className={"row"}>
                         // <div className="col-md-1">{this.props.orderId[0] !== null ? this.props.orderId[0] : " "}</div>                              
                                                         // ^^^^^^^^ you are trying to 
                                                         // access "0" index element of null
                            <div className="col-md-10"></div>
                            <div className="col-md-1"></div>
                        </div>
                        <div></div>
                    </div>

所以改变

<div className="col-md-1">{this.props.orderId[0] !== null ? this.props.orderId[0] : " "}</div> 

<div className="col-md-1">{this.props.orderId !== null ? this.props.orderId[0] : ""}</div>

<div className="col-md-1">{this.props.orderId && this.props.orderId[0]}</div>

两者都将检查orderId的值并执行某些操作。

在第二种情况下,如果orderId为null / false,它将不执行“ &&”运算符之后的代码;如果为非null / true,它将在“ &&”运算符之后执行代码,即它将首先返回或orderId中的索引元素“ 0”。