ReactJS:我的对象在构造函数获取数据之前呈现



作为一个ReactJS初学者,我正在尝试编写一个简单的单页WebApp。我的目的是从API获取数据并将其显示在我的网页上,因此我需要获取URL,将它们传递给我的孩子对象,然后再次获取数据。

显然,当URL的提取仍在发生时,孩子们的渲染开始。

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
          title: '',
          events: '',
          people: '',
      };
  }
  componentWillMount(){
    fetch('http://example.org/').then(response => response.json())
    .then(json => this.setState({
      title: json.title,
      events: json.events,
      people: json.people,
    }))
  }
render(){
   return (
      <div>
          <Child
            url= {this.state.events}
          />
          <Child
            url= {this.state.people}
          />
    );
}

这是可能的孩子之一:

class Child extends Component {
   constructor(props) {
      super(props);
      this.state = {
          collection: [],
      };
  }
    componentWillMount(){
      fetch(this.props.url, {
          method: 'GET',
          headers: {
              Accept: 'application/json',
          },
        },
      ).then(response => {
      if (response.ok) {
          response.json().then( json => this.setState({
              collection: json[Object.keys(json)[0]],
          }));
      }
  });
}

尝试运行应用程序时这些列表为空。值得注意的是,当在构造函数(或父派渲染(中进行了硬编码时,结构将完美工作。

所以我的问题是,有什么方法可以使我的渲染等待我的提取完成,或者有其他解决问题的方法?

1-使用componentDidMount生命周期方法获取数据而不是componentWillMount

2-要将rendering保存在子组件中,请在父组件中使用bool,它将告诉您状态是否已成功获取。

使用此:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            title: '',
            events: '',
            people: '',
            isDataFetched: false
        };
    }
    componentDidMount(){
        fetch('http://example.org/')
          .then(response => response.json())
          .then(json => this.setState({
              title: json.title,
              events: json.events,
              people: json.people,
              isDataFetched : true
          }))
    }
    render(){
        if(!this.state.isDataFetched) return null;
          return (
              <div>
                  <Child
                    url= {this.state.events}
                  />
                  <Child
                    url= {this.state.people}
                  />
              </div>
          );
    }
}

为什么您的代码不起作用?

componentWillMount方法在渲染之前仅被调用一次,您在父级组件中进行api呼叫,而子女组件中的fetch api取决于该fetch呼叫的数据,而父级fetch fetch call fetch fetch fetch fetch fetch fetch fetch fetch渲染和儿童组件的 componentWillMount被调用,因为这样的子组件中的提取呼叫不起作用。