当更改作为数组传递的道具时,React功能组件不会重新渲染

时间:2018-09-20 15:37:32

标签: javascript reactjs

当我传递数组作为道具并更改数组的值时,我的功能组件不会重新渲染。

https://codesandbox.io/s/5ym4vkrnnk

import React, { PureComponent, Fragment } from "react";
import ReactDOM from "react-dom";

const SomeFunctionalComponent = props => {
  return <span>{props.array[0]}</span>;
};

class App extends PureComponent {
  state = {
    array: [1, 2, 3]
  };
  increase = () => {
    var array = this.state.array;
    array[0] = array[0] + 1;
    this.setState({ array: array });
    console.log(this.state.array);
  };
  render() {
    return (
      <Fragment>
        <button onClick={this.increase}>Increase</button>
        <SomeFunctionalComponent array={this.state.array} />
      </Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我的问题:

  1. 为什么会这样?
  2. 我该如何更改?

感谢您的任何帮助!

1 个答案:

答案 0 :(得分:2)

从不直接更改状态

您正在直接在代码中更改状态,因此更改不会得到反映。数组成为对this.state.array的引用,这会导致意外的突变。

import React, { PureComponent, Fragment } from "react";
import ReactDOM from "react-dom";

const SomeFunctionalComponent = props => {
  return <span>{props.array[0]}</span>;
};

class App extends PureComponent {
  state = {
    array: [1, 2, 3]
  };
  increase = () => {
    var array = [...this.state.array];
    array[0] = array[0] + 1;
    this.setState({ array: array });
    console.log(this.state.array);
  };
  render() {
    return (
      <Fragment>
        <button onClick={this.increase}>Increase</button>
        <SomeFunctionalComponent array={this.state.array} />
      </Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);