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>
}
}
'React'メソッドを見てください:" shouldComponentUpdate "。 [LifeCycle](https://facebook.github.io/react/docs/react-component.html) – Tikkes
@TikkesこのAPIは私の問題を解決することができます、ありがとう – isbase