0

在控制台中,我得到两个输出,一个是空数组,另一个是更新后的数组。我只需要在组件执行挂载功能后更新数组。我怎样才能消除第一个......

class App extends Component {
  state={
    categories:[]
  };

  componentDidMount() { 
    axios.get(`https://s3.ap-south-1.amazonaws.com/scapic-others/json/models.json`)
      .then(response => {
             this.setState({categories:response.data.categories });
         })
    };

  render() {
    return (  
        <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" /></header>
          <h1 className="shake-opacity shake-freeze">3D models</h1>
         {console.log(this.state.categories)}
        </header>
        <footer className="pv4 ph3 ph5-m ph6-l red">
            <small className="f6 db tc">© 2018 <b className="ttu">Scapic Inc</b>., All Rights Reserved</small>
            <div className="tc mt3">
               {`Made by Renjith`}
            </div>
        </footer>
      </div>
    );
  }
}

export default App;
4

1 回答 1

2

您获得两个控制台输出的原因是因为componentDidMount is executed after render它触发了异步返回响应的 API 调用。一旦响应可用,您调用 setState 触发另一个渲染并因此触发第二个输出。

考虑到您需要的行为,您需要有一个加载状态,直到数据不可用时才会显示

class App extends Component {
  state={
    categories:[],
    isLoading: true
  };

  componentDidMount() { 
    axios.get(`https://s3.ap-south-1.amazonaws.com/scapic-others/json/models.json`)
      .then(response => 
        {this.setState({categories:response.data.categories, isLoading: false });
         })
    };


  render() {
    if (isLoading) {
        return <div>Loading...</div>
    }
    return (  
        <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" /></header>
          <h1 className="shake-opacity shake-freeze">3D models</h1>
         {console.log(this.state.categories)}





  <footer className="pv4 ph3 ph5-m ph6-l red">
            <small className="f6 db tc">© 2018 <b className="ttu">Scapic Inc</b>., All Rights Reserved</small>
            <div className="tc mt3">
               {`Made by Renjith`}
            </div>
        </footer>


      </div>



    );
  }
}

export default App;
于 2018-10-23T04:39:23.897 回答