如何根据 API 数据设置初始 React 状态?

新手上路,请多包涵

我有一个休息 API 后端设置。我想在组件的 getInitialState 函数中设置值,但我不知道如何填充我需要返回的对象,因为我使用的是异步 http 请求。正如预期的那样,我返回的对象具有未定义的值。我该如何解决这个问题?

我现在正在使用 fetch(老实说,可以切换到任何其他库)。我不知道如何调用 getInitialState 在异步调用返回一些值之后而不是在它发生之前。

 import React from 'react';
import 'whatwg-fetch';

export default class IndexPage extends React.Component {

  render() {

    // I basically need to call getInitialState after the last promise has been resolved
    fetch('https://localhost:3000/api/aye')
    .then(function(response) {
      return response.json();
    })
    .then(function(json) {
      // Need to return some values from this.
    });

    return (
      <div>
        <h1>{this.state.jsonReturnedValue}</h1>
      </div>
    );
  }
}

提前致谢!

原文由 Zeokav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 490
2 个回答

您应该调用 this.setState 以更改 state

 export default class IndexPage extends React.Component {

  constructor() {
    super();

    this.state = {
      jsonReturnedValue: null
    }
  }

  componentDidMount() {
    fetch('https://localhost:3000/api/aye')
      .then(response => response.json())
      .then(json => {
        this.setState({ jsonReturnedValue: json });
      });
  }

  render() {
    return (
      <div>
        <h1>{ this.state.jsonReturnedValue }</h1>
      </div>
    );
  }
}

原文由 Oleksandr T. 发布,翻译遵循 CC BY-SA 3.0 许可协议

在你的情况下 -

最好是第一次使用空状态数据完成渲染让我们说

constructor(props){
    super(props);

    this.state = {
        data : []
    };
}

并在 componentDidMount 中进行 ajax 调用,这是您可以执行 dom 操作并发送 ajax 请求通过 REST 获取数据的地方

从服务器获取新数据后,使用新数据设置状态

this.setState({data:newDataFromServer});

例如在 componentDidMount

 componentDidMount() {
 sendAjaxRequest()
 .then(
      (newDataFromServer) => {
              this.setState({data : newDataFromServer });

     });
}

这将导致使用从服务器获取的最新数据进行 重新渲染,并反映新的状态更改。

原文由 WitVault 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题