读取jsx中的数组值

问题描述 投票:0回答:1

在我的Next.JS应用程序中,我将一个数组作为支持传递给OrderViewer组件,但是当我尝试在JSX中读取传递数组的项时,会抛出以下错误。

未处理的拒绝(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>)
}
arrays reactjs
1个回答
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,它将在“&&”运算符之后执行代码,即它将返回第一个或“0”索引元素orderId

© www.soinside.com 2019 - 2024. All rights reserved.