2016-10-05 53 views
8

我刚开始看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接收数据的新状态?目前状态没有设置?

jsbin裁判:https://jsbin.com/tizalu/edit?js,console,output

+0

直接从诺言调用'setState'而不通过道具 – mguijarr

回答

5

的约定是使在componentDidMount生命周期方法的AJAX调用。看一看的阵营文档:通过AJAXhttps://facebook.github.io/react/tips/initial-ajax.html

加载初始数据
在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')); 

这里是在实现这一目标使用1)jQuery的两种方式; 2)爱可信库的另一个演示(http://codepen.io/PiotrBerebecki/pen/dpVXyb)。

全码:

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') 
); 
+0

我刚刚添加了您的代码,并对我的aswer进行了必要的更改。 https://jsbin.com/cijafi/edit?html,js,output您想让我添加任何内容吗?还是回答您的问题? –

+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(); 
    } 
}); 

谢谢!

+0

请让我知道它是否适合你! –