我正在尝试在react中实现异步XMLHttpRequest。
这是我的尝试:
var xhr = new XMLHttpRequest();
var json_obj, status = false;
xhr.open("GET", "https://jsonplaceholder.typicode.com/photos/", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
json_obj = xhr.responseText;
status = true;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
class Welcome extends React.Component {
render() {
return (
<div>
<img src= {status ? json_obj[0].url : 'loading...'}></img>
</div>
);
}
}
ReactDOM.render(
<Welcome/>,
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>
我一直在考虑添加监听器,但我不知道该怎么做。
总的来说,我在异步 XMLHttpRequest 加载并返回值后遇到更新问题。
建议在以下位置进行 AJAX 调用componentDidMount
生命周期方法。
componentDidMount
是为了副作用。添加事件监听器、AJAX、改变 DOM 等。
另外,您应该考虑使用新的fetch API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
class Welcome extends React.Component {
constructor() {
this.state = {
data: null,
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/photos/').then(response => {
return response.json();
}).then(json => {
this.setState({ data: json});
}).catch(error);
}
render() {
if (this.state.data) {
return <img src={this.state.data[0].url} />
}
else {
return <div>Loading...</div>
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)