gpt4 book ai didi

javascript - 无法弄清楚如何使用 {this.props.etc} 尤其是 React.js 中的 map

转载 作者:行者123 更新时间:2023-12-03 09:45:46 24 4
gpt4 key购买 nike

var Order = React.createClass({
loadOrderFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
this.setState({data:data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadOrderFromServer();
setInterval(this.loadOrderFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="orderInformationTable">
<table>
<thead>
<tr>
<th width="200">General Info</th>
<th> </th>
</tr>
</thead>
<tbody>
<OrderInformationTable order={this.state.data.order} />
</tbody>
</table>
</div>
);
}
});



var OrderInformationTable = React.createClass({
render: function() {

var orderInfo = this.props.order.map(function (info) {
return (
<tr>
<td>{info.attribute}</td>
<td>{info.value}</td>
</tr>
)
});

return (
<div className="orderInfoTableContents">
{orderInfo}
</div>
);
}
});

React.render(
<Order url="api_url" pollInterval={2000} />,
document.getElementById('order')
);

//来自api的数据格式如下

{
"order":[
{"attribute":"id","value":2066},
{"attribute":"name","value":"John D."},
{"attribute":"location","value":"USA"},
],
"pieces":[
{"id":2,"type":"Diamond Ring","status":null,
"items":[
{"id":3,"type":"setting","style":"solitaire"},
{"id":2,"type":"setting","style":"style 3"} ],
"tasks":[
{"number":1,"task":"order diamond","description":"for diamond 43","status":"in progress"} ]
} <-- end of a single "piece"
] <-- end of array of "pieces"
}

我收到的错误是:类型错误:this.props.order 未定义

我成功地使用静态虚拟数据完成了这件事,其中所有内容都是 Prop ,但现在我正在使用状态,它不起作用,而且我无法找出错误。

此外,我可以访问 OrderInformationTable 中的 this.props.order 来显示它,但我无法用它做任何事情。因此,我不确定我是否理解这个对象的本质。我确信 api 和 this.state.data 中的数据是正确的。预先感谢任何能够阐明这一点的人!

最佳答案

正如我在评论中所说,OrderInformationTableajax 请求完成之前呈现,这会导致在开始时没有任何 Prop 传递给该子组件。

解决这个问题的一种方法是:

var OrderInformationTable = React.createClass({
render: function() {
var orderInfo;
if (this.props.order) {

orderInfo = this.props.order.map(function (info) {
return (
<tr>
<td>{info.attribute}</td>
<td>{info.value}</td>
</tr>
)
});
}
return (
<div className="orderInfoTableContents">
{orderInfo}
</div>
);
}
});

它是这样工作的:
- React 组件有 lifecycles 。您正在使用代码执行的操作是等待组件被安装,然后启动 ajax 请求,该请求(顾名思义)是异步的。
那么会发生什么?
好吧,您的组件已安装,此时您的 state 中没有 data,因此您没有向 OrderInformationTable 发送任何内容,因此当您尝试mapthis.props.order 并发生错误,因为此时没有 this.props.order。如果您避免此错误,通过检查 this.props.order 是否已定义或任何其他方式来避免此错误,您将是安全的,因为在您的 ajax 请求 完成后,您将获取您的数据,您的状态将通过props传递到OrderInformationTable,并且您的组件将更新并呈现您的新内容。

希望这能让你摆脱困境。

关于javascript - 无法弄清楚如何使用 {this.props.etc} 尤其是 React.js 中的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com