'React component props does not update as expected when concatented with redux

The peoblem is hard to describe so please kindly view the code and results:)

Level1.tsx:

import React from "react";
import Level2 from "./Level2";

interface Level1State {
  listExample: {
    name: string;
    value: number;
  }[];
}

class Level1 extends React.Component<{}, Level1State> {
  public state: Level1State = {
    listExample: [
      { name: "a", value: 1 },
      { name: "c", value: 2 },
      { name: "e", value: 3 },
    ],
  };

  public componentDidUpdate() {
    console.log('Level 1 has updated!');
  }

  private setVal = () => {
    this.setState((prevState: Level1State) => {
      const listExample = prevState.listExample;
      listExample[0].name = 'asd';
      return { listExample };
    }, () => { console.log(this.state.listExample) });
  };

  private realSetVal = () => {
    this.setState((prevState: Level1State) => {
      const listExample = JSON.parse(JSON.stringify(prevState.listExample));
      listExample[1].name = 'fgh';
      return { listExample };
    }, () => { console.log(this.state.listExample) });
  };

  public render() {
    return (
      <>
        <Level2 listExample={this.state.listExample} />
        <button onClick={this.setVal}>Change State Value (Wrong)</button>
        <button onClick={this.realSetVal}>Change State Value (Right)</button>
      </>
    );
  }
}

export default Level1;

Level2.tsx:

import React from "react";
import { connect } from "react-redux";

interface Level2Props {
  listExample: {
    name: string;
    value: number;
  }[];
}

class Level2 extends React.Component<Level2Props, {}> {
  public componentDidUpdate() {
    console.log("Level 2 has updated!");
  }

  public render() {
    return (
      <ul>
        {this.props.listExample.map((item) => {
          return (
            <li key={item.name}>
              {item.name}-{item.value}
            </li>
          );
        })}
      </ul>
    );
  }
}

// export default connect(() => {})(Level2);
export default Level2;

Here's the different results after clicking each button when using connect and not

I know the shallow copy in setVal is not correct, which might be the cause. But I don't understand why a connect makes such difference.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source