代码之家  ›  专栏  ›  技术社区  ›  Pavindu

读取jsx中的数组值

  •  0
  • Pavindu  · 技术社区  · 7 年前

    在我的Next.JS应用程序中,我将一个数组作为道具传递给 OrderViewer

    未处理的拒绝(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 回复  |  直到 7 年前
        1
  •  1
  •   Sahil Raj Thapa    7 年前

    在代码中, Orders 组件具有 state

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

    你通过了 组件状态作为 OrderViewer 组成部分

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

    在…内 组成部分

     // 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 做了些什么。

    在第二种情况下,如果 医嘱ID 如果为null/false,它将不会在“&”运算符之后执行代码,如果不是null/true,它将在“&”运算符之后执行代码,即它将从 医嘱ID