如何在React中使用setState更新数据?

13

我刚开始学习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收到的数据更新状态?目前状态未设置。

jsbin参考:https://jsbin.com/tizalu/edit?js,console,output


直接从 Promise 中调用 setState,而不通过 props。 - mguijarr
2个回答

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

我刚刚将您的代码进行了必要的更改并添加到我的答案中。https://jsbin.com/cijafi/edit?html,js,output 您需要我添加其他内容吗?还是已经回答了您的问题? - Piotr Berebecki

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

谢谢!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接