我試圖循環通過json_obj加載後使用async XMLHttpRequest()
,但因爲json_obj在啓動map()崩潰時爲null。等待對象數組加載並映射()它。 React
這裏是我的代碼:
import React, { Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
class ImageViewer extends React.Component {
constructor() {
super();
this.state = {
loading: true,
json_obj : null,
link: "https://api.github.com/users/github/repos"
}
}
componentDidMount() {
var xhr = new XMLHttpRequest();
xhr.open("GET", this.state.link, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
this.setState({ json_obj :JSON.parse(xhr.responseText).sort(function(a, b){var keyA = new Date(a.updated_at),keyB = new Date(b.updated_at);if(keyA > keyB) return -1;if(keyA < keyB) return 1;return 0;})});
} else {
console.error(xhr.statusText);
}
}
}.bind(this);
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
render() {
return (
<div>
{this.state.json_obj.map((obj, index) => {
return (
<div >
<h1>{obj.name}</h1>
<h1>{obj.updated_at}</h1>
</div>
)
})}
</div>
)
}}
ReactDOM.render(
<ImageViewer />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
: <div id="root"></div>
我試圖用條件呈現,但它拋出的錯誤,以及:
import React, { Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
class ImageViewer extends React.Component {
constructor() {
super();
this.state = {
loading: true,
json_obj : null,
link: "https://api.github.com/users/github/repos",
stuff : {name:"loading", updated_at:"loading"}
}
}
componentDidMount() {
var xhr = new XMLHttpRequest();
xhr.open("GET", this.state.link, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
this.setState({ json_obj :JSON.parse(xhr.responseText).sort(function(a, b){var keyA = new Date(a.updated_at),keyB = new Date(b.updated_at);if(keyA > keyB) return -1;if(keyA < keyB) return 1;return 0;})});
} else {
console.error(xhr.statusText);
}
}
}.bind(this);
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
render() {
return (
<div>
{(this.state.json_obj ? this.state.json_obj : this.state.stuff).map((obj, index) => {
return (
<div >
<h1>{obj.name}</h1>
<h1>{obj.updated_at}</h1>
</div>
)
})}
</div>
)
}}
ReactDOM.render(
<ImageViewer />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
什麼錯誤(S),你接受? – cbronson
json_obj未定義/ null。 @Dominic Tobias解決方案工作。只是不能接受它。 – Mac