isbase
isbase

Reputation: 71

How to avoid repeated rendering of react component?

The startUpload method inside <Items /> will call the callback function to update the state of the parent component each time it receives a response, This causes <Items /> to be rendered unnecessarily multiple times.

My expected effect is that after the state is updated, only the <Results /> component needs to be re-rendered

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>
    }
}

Upvotes: 3

Views: 961

Answers (1)

Dave Cooper
Dave Cooper

Reputation: 10714

https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate You can use shouldComponentUpdate to inform your component whether or not should re-render or not based on a change in state/props. Using this knowledge, you can implement the logic you need in order to render the Items/Results component only when needed.

Hope that helps!

Upvotes: 2

Related Questions