componentdidmount完成后渲染

时间:2019-11-13 08:12:32

标签: javascript reactjs frontend

我正在尝试将fileList值更新为Upload组件。但是,handleOne函数始终显示[]。从控制台上,我可以看到handleOne函数先于getFirebaseURL函数执行。有没有一种方法可以让我等到componentDidMount完成所有setState方法,然后呈现页面?我尝试使用componentWillMount()shouldUpdate(),但它们都不起作用。谁能帮我? 非常感谢!

handleOne = () => {
  console.log(this.state.data)
}

componentDidMount() {
  axios.get('/user/product')
    .then(res=>{
      if(res.data.code==0) {
        this.setState({data:res.data.data}, function(){
          for(i = 0; i < 10; i++) {
             // this getURL function also contains setState
             this.getFirebaseURL(this.state.data[i].productName) 
          }
        })
      }
    })
}


render(){
  <Upload fileList= {this.handleOne()}>
  </Upload>
}

已更新

 getFirebaseURL = product => {
   // Get all the images from the firebase
    var storage = firebase.storage();
    var that = this;
    var i = 0;
    const storageRef =  storage.ref(`image/${product}`)

    // Get all the URL
    storageRef.listAll().then(function(result) {
      result.items.forEach(function(imageRef) {
        imageRef.getDownloadURL().then(function(url) {  

              i = i + 1;
              let object = {}
              object['uid'] = i.toString();
              object['name'] = product;
              object['url'] = url;

              let list = []
              list.push(object)
              // temp3 is an array        
              that.state.temp3.push(list)
            }).catch(function(error) {});        
         })
       })          
    }

2 个答案:

答案 0 :(得分:0)

使用如下所示的条件渲染:

render(){
  {this.state.data && <Upload fileList= {this.handleOne()}> }
  </Upload>
}

答案 1 :(得分:0)

您应该从componentDidMount函数中提取te get函数。我称它为getUser()。

first - second

此函数返回一个promise,您需要在componentDidMount()中等待它。

  getUser = () => {
    return axios.get("/user").then(res => {
      if (res.data.code == 0) {
        this.setState({ data: res.data.data }, function() {
          // this getURL function also contains setState
          this.state.data.map(i => this.getFirebaseURL(i));
        });
      }
    });
  };
相关问题