我刚开始研究 reactjs 并尝试从 API 检索数据:
constructor(){
super();
this.state = {data: false}
this.nextProps ={};
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
nextProps= response;
});
}
当promise返回数据时,我想把它赋值给状态:
componentWillReceiveProps(nextProps){
this.setState({data: nextProps})
}
如何使用从 API 接收到的数据更新状态?目前状态未设置?
最佳答案
约定是在 componentDidMount
生命周期方法中进行 AJAX 调用。查看 React 文档:https://facebook.github.io/react/tips/initial-ajax.html
Load Initial Data via AJAX
Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.
因此您的代码将变为:https://jsbin.com/cijafi/edit?html,js,output
class App extends React.Component {
constructor() {
super();
this.state = {data: false}
}
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
this.setState({data: response.data[0].title})
});
}
render() {
return (
<div>
{this.state.data}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
这是另一个演示 (http://codepen.io/PiotrBerebecki/pen/dpVXyb),展示了使用 1) jQuery 和 2) Axios 库实现此目的的两种方法。
完整代码:
class App extends React.Component {
constructor() {
super();
this.state = {
time1: '',
time2: ''
};
}
componentDidMount() {
axios.get(this.props.url)
.then(response => {
this.setState({time1: response.data.time});
})
.catch(function (error) {
console.log(error);
});
$.get(this.props.url)
.then(result => {
this.setState({time2: result.time});
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div>
<p>Time via axios: {this.state.time1}</p>
<p>Time via jquery: {this.state.time2}</p>
</div>
);
}
};
ReactDOM.render(
<App url={"http://date.jsontest.com/"} />, document.getElementById('content')
);
关于javascript - 如何在 react 中将状态设置为新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39866876/