[英]React functional component doesnt rerender when changing props passed as an array
My functional Component doesn't rerender when i pass an array as it's props and change the values of the array. 当我传递数组作为道具并更改数组的值时,我的功能组件不会重新渲染。
https://codesandbox.io/s/5ym4vkrnnk https://codesandbox.io/s/5ym4vkrnnk
or 要么
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);
My questions: 我的问题:
Thanks for any help in advance! 感谢您的任何帮助!
Never Mutate the state directly 从不直接改变状态
you are mutating the state directly in your code so the changes are not getting reflected. 您直接在代码中更改状态,因此更改不会得到反映。 Array becomes a reference to this.state.array, which causes the undesired mutation. Array成为对此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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.