api响应后渲染反应组件

r_c*_*ill 13 javascript dropbox-api reactjs

我有一个反应组件,我希望使用Dropbox api填充图像.api部分工作正常,但组件在数据通过之前呈现,因此数组为空.如何在组件具有所需数据之前延迟组件的渲染?

var fileList = [];
var images = [];
var imageSource = [];

class Foo extends React.Component {

 render(){
  dbx.filesListFolder({path: ''})
  .then(function(response) {
   fileList=response.entries;
   for(var i=0; i<fileList.length; i++){
    imageSource.push(fileList[0].path_lower);
   }
   console.log(imageSource);
   })

  for(var a=0; a<imageSource.length; a++){
   images.push(<img key={a} className='images'/>);
  }

  return (
   <div className="folioWrapper">
    {images}
   </div>
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

May*_*kla 19

变化:

1.不要在render方法中执行api调用,componentDidMount为此使用生命周期方法.

componentDidMount:

在装入组件后立即调用componentDidMount().需要DOM节点的初始化应该放在这里.如果需要从远程端点加载数据,这是实例化网络请求的好地方.在此方法中设置状态将触发重新渲染.

2.imageSource使用初始值在状态数组中定义变量[],一旦获得使用setState的响应更新,它将自动使用更新的数据重新呈现组件.

3.使用state数组在render方法中生成ui组件.

4.要保持渲染直到你没有得到数据,将条件置于render方法内,imageSource如果长度为零则检查数组的长度return null.

写这样:

class Foo extends React.Component {

    constructor(){
        super();
        this.state = {
            imageSource: []
        }
    }

    componentDidMount(){
        dbx.filesListFolder({path: ''})
          .then((response) => {
              let fileList = response.entries;
              this.setState({
                  imageSource: fileList
              });
          })
    }

    render(){
        if(!this.state.imageSource.length)
            return null;

        let images = this.state.imageSource.map((el, i) => (
            <img key={i} className='images' src={el.path_lower} />
        ))

        return (
            <div className="folioWrapper">
                {images}
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


Don*_*anM 6

您应该使用组件的状态或道具,以便在更新数据时重新呈现.对Dropbox的调用应该在render方法之外完成,否则每次组件重新渲染时你都会遇到API.这是你可以做的一个例子.

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imageSource: []
    }
  }

  componentDidMount() {
    dbx.filesListFolder({ path: '' }).then(function(response) {
      const fileList = response.entries;

      this.setState({
        imageSource: fileList.map(file => file.path_lower);
      })
    });
  }

  render() {
    return (
      <div className="folioWrapper">
        {this.state.imageSource.map((image, i) => <img key={i} className="images" src={image} />)}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果还没有图像,它只会以div这种方式呈现空白.


Fra*_*teo 0

首先,您应该使用组件的状态而不是使用全局定义的变量。

因此,为了避免显示带有空图像数组的组件,您需要在组件上应用条件“加载”类,并在数组不再为空时将其删除。