如何避免反应组件的重复渲染?

时间:2016-12-06 09:47:57

标签: javascript reactjs

startUpload内的<Items />方法将调用回调函数,以便在每次收到响应时更新父组件的状态,这会导致<Items />多次不必要地呈现。

我的预期效果是在状态更新后,只需要重新呈现<Results />组件

&#13;
&#13;
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>
    }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate您可以使用shouldComponentUpdate通知您的组件是否应根据状态/道具的更改重新呈现。使用这些知识,您可以实现所需的逻辑,以便仅在需要时呈现Items / Results组件。

希望有所帮助!