javascript - 如何避免重复渲染 React 组件?

标签 javascript reactjs

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

最佳答案

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

希望对您有所帮助!

关于javascript - 如何避免重复渲染 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40992304/

相关文章:

javascript - 关于javascript中函数作为值概念的混淆

javascript - 如何使用基于 3 个独立输入的 Javascript 检查用户的年龄

Javascript/JQuery 如果样式显示值等于

reactjs - 元素引用被指定为字符串 (clickAwayableElement),但未设置所有者

javascript - 侧边栏 DOM 与 Navbar 重叠,将其从 DOM 中移除

javascript - 如何让 map 移动时标记始终居中?

javascript - 当值与显示值不同时,标签上的 Select2 错误

javascript - 选择列表在选择时不触发 jquery

javascript - React 在等待 API 调用返回数据时实现事件轮

javascript - 从 DOM 控制 React 组件 props