ReactJS:渲染数组的块

时间:2017-03-26 19:12:01

标签: javascript reactjs

设置为es6 class:

export default class Gallery extends Component {
  addPhotos() {
    let data = [{}, {}, {}, {}, {}, {}]; // array of objects
    let dataChunks = chunk(data, 2); // returns array of two arrays [[{}, {}, {}],[{}, {}, {}]]

 // now here is where I am stuck. I want to:

  return dataChunk[0].map((photo) => (
    <PhotoComponent key={photo._id} photo={photo} />
  ));

 // wait 500ms and then add 3 more photos to the gallery (essentially throttling the loading)

  return dataChunk[1].map((photo) => (
    <PhotoComponent key={photo._id} photo={photo} />
  ));

理想情况下,我可以加载3张照片,然后在500毫秒后添加下3张照片。

作为奖励,在两者之间加载组件......

思想?

我尝试过:

1)使用state来存储数组。问题似乎是渲染数组并更改它会导致堆栈溢出问题。

2)使用带有setTimeout的for循环......出于某种原因,组件props变为未定义。

2 个答案:

答案 0 :(得分:2)

维护一个state变量,检查是否render array的下一部分,并使用超时来更改该变量的状态,它应该有效,写一样这样:

export default class Gallery extends Component {
    constructor(){
        super();
        this.state(
            renderNext: false,
            data: [{}, {}, {}, {}, {}, {}]
        )
    }

    _renderFisrtPart(){
        let data = this.state.data, arr = [];
        for(let i = 0; i < data.length/2; i++){
            arr.push(<PhotoComponent key={data[i]._id} photo={data[i]} />)
        }
        setTimeout(()=>{this.setState(renderNext: true)}, 500);
        return arr;
    }

    _renderSecondPart(){
        if(!this.state.renderNext) return;

        let data = this.state.data, arr = [];
        for(let i = data.length/2; i < data.length; i++){
            arr.push(<PhotoComponent key={data[i]._id} photo={data[i]} />)
        }

        return arr;
    }

    render(){
        return(
            <div>
                {this._renderFisrtPart()}
                {this._renderSecondPart()}
            </div>
        )
    }
}

答案 1 :(得分:1)

这是我的方法,在setTimeout方法中使用componentDidMount。你也可以将它包装在一个Promise中并用addDatathen

export default class Gallery extends Component {
  constructor(props) {
    super(props);

    this.addData = this.addData.bind(this);

    this.state = { data: [] };
  }

  componentDidMount() {
    // Don't know if you're getting your data via props
    const data = this.props.data || [{}, {}, {}, {}, {}, {}];
    const chunks = chunk(data, 2);

    this.addData(chunks[0])();
    setTimeout(this.addData(chunks[1]), 500);
  }

  addData(data) {
    return () => this.setState({
      data: [
        ...this.state.data,
        ...data,
      ],
    });
  }

  render() {
    return this.state.data.map(photo => <PhotoComponent key={photo._id} photo={photo} />);
  }
}