Reputation: 43
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
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!
Upvotes: 1
Views: 1297
Reputation: 5486
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.
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);
Upvotes: 3