首页 > 解决方案 > 反应 shouldComponentUpdate 新旧道具相同

问题描述

在我的代码中,有一个子组件从父组件接收道具,我正在映射该数组以渲染其名称,添加图像按钮和一个子组件用于渲染图像(这是为了避免重新渲染图像)。

当我添加图像时,孩子的孩子重新渲染它工作正常,但是当我通过孩子的孩子删除按钮删除图像时,图像会从父状态中删除,但孩子的孩子不会重新渲染,因为 shouldComponentUpdate 的旧道具和新道具将是相同的。

谁能建议为什么会这样?

子组件

import { TextField } from "@material-ui/core";
import React, { Component } from "react";

export default class ShowData extends Component {
  shouldComponentUpdate(newProps) {
    return !(this.props.data === newProps.data);
  }
  render() {
    const data = this.props.data; //this get data in array like [{name: "test", images: [..images]},{name: "test2", images: [..images]}]
    const update = this.props.update; //this will receive parent function for update state parameters (target, index, value,img-removeIndex)
    return (
      <div>
        {data.map((user, key) => {
          return (
            <>
              <TextField
                fullWidth
                id="outlined-basic"
                onChange={(e) => this.props.update("NAME", key, e.target.value)}
                value={user.name}
                variant="outlined"
              />
              <UserImages
                images={user.images}
                index={key}
                remove={this.props.update}
              />{" "}
              //child component
              <input
                type="file"
                onChange={(e) =>
                  this.props.update("ADD_IMG", key, e.target.files)
                }
              />
            </>
          );
        })}
      </div>
    );
  }
}

Child的子组件

import React, { Component } from "react";

export default class UserImages extends Component {
  shouldComponentUpdate(newProps) {
    return !(this.props.images === newProps.images);
  }
  render() {
    const remove = this.props.remove;
    return (
      <div>
        {this.props.images.map((img, key) => {
          return (
            <>
              <img src={img} />
              <button
                onClick={() => remove("REMOVE_IMG", this.props.index, "", key)}>Remove
              </button>
            </>
          );
        })}
      </div>
    );
  }
}

为什么当我控制台新旧道具时新旧道具相同然后图像被删除但新旧道具值是新更新的图像状态值。这就是为什么它不会重新渲染但删除的图像仍然显示

标签: reactjsreact-class-based-component

解决方案


推荐阅读