在componentDidMount之前和之后获取两个输出

时间:2018-10-23 04:36:30

标签: reactjs react-lifecycle

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

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;

1 个答案:

答案 0 :(得分:2)

获得两个控制台输出的原因是因为componentDidMount is executed after render触发了一个API调用,该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;