在我的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>)
}
在你的代码中,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
。