当我传递数组作为道具并更改数组的值时,我的功能组件不会重新渲染。
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);
我的问题:
感谢您的任何帮助!
答案 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);