2016-12-06 17 views
2

startUpload内のメソッド<Items />は、レスポンスを受信するたびに親コンポーネントの状態を更新するコールバック関数を呼び出します。これにより、<Items />が不必要に複数回レンダリングされます。反応成分の繰り返しレンダリングを避けるには?

私の期待される効果は、状態が更新された後、唯一の<Results />コンポーネントは、あなたはかどうか、あなたのコンポーネントに通知するためにshouldComponentUpdateを使用することができます

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

答えて

2

https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdateを再レンダリングする必要があるということです状態/小道具の変更に基づいて再レンダリングする必要があります。この知識を使用して、必要なときにのみItems/Resultsコンポーネントをレンダリングするために必要なロジックを実装できます。

希望に役立ちます!

関連する問題