[英]React.js, HTML, CSS: can't figure out why align-items doesn't work
[英]Can't figure out how to work with {this.props.etc} especially with map in React.js
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"
}
我得到的錯誤是:TypeError:this.props.order未定義
我使用所有對象都是道具的靜態虛擬數據成功完成了此操作,但是現在我正在使用狀態,它無法正常工作,而且我無法弄清錯誤。
另外,我可以訪問OrderInformationTable中的this.props.order來顯示它,但是我無法執行任何操作。 因此,我不確定我是否了解該對象的本質。 而且我確定api和this.state.data中的數據正確。 預先感謝任何可以闡明這一點的人!
正如我在評論中所說, OrderInformationTable
是在ajax請求完成之前呈現的,這導致在開始時沒有將道具蜂傳遞給此子組件。
解決此問題的一種方法是:
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組件具有生命周期 。 您在執行代碼時所要做的就是等待組件被掛載,然后啟動ajax請求(顧名思義)是異步的。
那會怎樣呢?
好了,您的組件已安裝,並且此時您的state
沒有data
,因此您不向OrderInformationTable
發送任何內容,因此當您嘗試通過this.props.order
進行map
時會發生錯誤,因為在此點上沒有this.props.order
。 如果避免此錯誤,則可以通過檢查是否已定義this.props.order
或通過其他任何方式避免此錯誤的方法來確保安全,因為在ajax請求完成后,您將獲取data
,狀態將通過props
傳遞給OrderInformationTable
然后您的組件將更新並呈現您的新內容。
希望這能把您清除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.