MENU
Updating Complex State
Make sure you set the state properly if you wish to cause a re-render.
RESETRUNFULL
class ListOfWords extends React.PureComponent {
render() {
return <div>{this.props.words.join(',')}</div>;
}}class WordAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
words: ['marklar']
};
this.handleClick = this.handleClick.bind(this);
} // BUG! This won’t update ListOfWords as 'words' still points to the same object //handleClick() { //
const words = this.state.words; //
words.push('marklar'); //
this.setState({words: words}); //}
handleClick() {
this.setState(state=>({words:[...state.words, 'extravagant' ]}));
}
render() {
return (<div><button onClick={this.handleClick} >Add</button>
<ListOfWords words={this.state.words} /></div>);
}}ReactDOM.render(<WordAdder/>,document.querySelector("div"));
To update an array element:
RESETRUNFULL
// WRONG! Mutating state in place!//handleChange = (e) => {//
const { items } = this.state;//
items[1].name = e.target.value;//
this.setState({ items });//};handleChange = (e) => {
const newItems = [...this.state.items];
newItems[item].name = e.target.value;
this.setState({ items:newItems });};