React - 从api设置初始状态

Zeo*_*kav 17 javascript reactjs

我有一个休息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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ale*_* T. 18

你应该打电话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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Wit*_*ult 5

在你的情况下——

最好使用空状态数据第一次完成渲染

constructor(props){
    super(props);

    this.state = {
        data : []
    };
}
Run Code Online (Sandbox Code Playgroud)

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

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

this.setState({data:newDataFromServer});
Run Code Online (Sandbox Code Playgroud)

例如在componentDidMount

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

     });
}
Run Code Online (Sandbox Code Playgroud)

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