2016-12-06 88 views
2

startUpload方法內<Items />將調用回調函數來更新在每次接收到的響應時間的父組件的狀態,這將導致<Items />不必要地多次渲染。如何避免重複渲染反應組件?

我預期的效果是,狀態更新後,只有<Results />組件需要重新呈現

class Parent extends React.Component { 
 
    constructor(props) { 
 
     super(props); 
 
     this.getResponseData = this.getResponseData.bind(this); 
 
     this.state = { 
 
      responseData: [], 
 
     } 
 
    } 
 
    
 
    getResponseData(data) { 
 
     this.setState({ 
 
      responseData: this.state.responseData.concat(data), 
 
     }) 
 
    } 
 

 
    render() { 
 
     return (
 
      <div> 
 
       <Items files={this.props.files} updateData={this.getResponseData}/> 
 
       <Results data={this.state.responseData}/> 
 
      </div> 
 
     ) 
 
    } 
 
} 
 

 
class Items extends React.Component { 
 
    componentDidMount() { 
 
     this.startUpload(this.props.files) 
 
    } 
 

 
    startUpload(files) { 
 
     const URL = 'http://localhost:3000/upload'; 
 

 
     for (let i = 0, len = files.length; i < len; i++) { 
 
      const data = new FormData(); 
 
      data.append('img', files[i]); 
 

 
      fetch(URL, { 
 
       method: 'post', 
 
       body: data, 
 
      }) 
 
       .then(checkStatus) 
 
       .then(parseJSON) 
 
       .then(data => { 
 
        this.props.updateData(data); 
 
       }) 
 
     } 
 
    } 
 

 
    render() { 
 
     const filesData = this.getFilesData(this.props.files); 
 

 
     let imageItems = filesData.map((current) => { 
 
      return (
 
       <div> 
 
        <img src={current.objectURL} alt="preview"/> 
 
       </div> 
 
      ) 
 
     }); 
 

 
     return <div>{imageItems}</div>; 
 
    } 
 
} 
 

 
function Results(props) { 
 
    const responseData = props.data; 
 
    let result = []; 
 

 
    if (responseData.length) { 
 
     result = responseData.map(current => { 
 
      return <p>{current}</p> 
 
     }); 
 

 
     return <div>{result}</div> 
 
    } 
 
}

+0

查看'React'方法:「shouldComponentUpdate」。 [LifeCycle](https://facebook.github.io/react/docs/react-component.html) – Tikkes

+0

@Tikkes這個API可以解決我的問題,謝謝 – isbase

回答