我刚开始查看reactjs并尝试通过api检索数据:
constructor(){
super();
this.state = {data: false}
this.nextProps ={};
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
nextProps= response;
});
}
当承诺回来时,我想将数据分配给状态:
componentWillReceiveProps(nextProps){
this.setState({data: nextProps})
}
如何使用从api收到的数据设置新状态?目前国家没有设定?
答案 0 :(得分:8)
惯例是在componentDidMount
生命周期方法中进行AJAX调用。请查看React文档:https://facebook.github.io/react/tips/initial-ajax.html
通过AJAX加载初始数据
获取componentDidMount中的数据。响应到达时,将数据存储在状态中,触发渲染 更新你的用户界面。
因此,您的代码将变为: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')
);
答案 1 :(得分:4)
您可以尝试使用以下示例代码,如果您需要任何进一步的帮助,请告诉我。
var YourComponentName = React.createClass({
componentDidMount: function() {
var that = this;
// Your API would be calling here and get response and set state here as below example
// Just an example here with AJAX something you can do that.
$.ajax({
url: 'YOURURL',
dataType: 'json',
type: 'POST',
data: data,
success: function(response) {
that.setState({data: response})
}
});
},
render: function() {
return ();
}
});
谢谢!