Gustė
Gustė

Reputation: 137

State is changed, but Component doesn't reload

I have a button Refresh witch should change state in the Component and it should re-render it's child component Excercise. The state changes, I can see in console.log, but why there's no rerendering of chd Component? (if you put smth in input and click Refesh, nothing happens)

class ListComponent extends React.Component{
    constructor(props){
        super(props);

        this.state = {reload: true};
    };

    refreshComponent(){
        if (this.state.reload){ 
            this.setState({reload: false })  
            console.log(this.state.reload);

        } else if (!this.state.reload) {
            this.setState({reload: true })
            console.log(this.state.reload);  
        }
    };
    render () {
        return (
        <div>   
           {WordList.map(word => {
                return <li><Excercise wordObject={word}></Excercise></li>})  }

                <button onClick={()=>this.refreshComponent()}>Refresh</button>
        </div>
        )
    }
}

export default ListComponent;

//chd component:

class Excercise extends React.Component {
render(){
    return (<div>
            <table>
                <tbody>
                    <td>
                        {this.props.wordObject.danishWord}
                        <input 
                        type={'text'} 
                        ></input>
                    </td>
                </tbody>
            </table>   
        </div>     
    )
}

Upvotes: 1

Views: 6107

Answers (1)

Andrea
Andrea

Reputation: 1316

There is a misconception of the meaning of rerender.

Problem

When you change the state in the parent component, the child gets rerendered, but it doesn't destroy it, so the value stays there.

Explanation

Rerendering a Component, doesn't mean to destroy it and create it again. It just notifies it that something has changed and that the react engine has to check for any view differences.

https://reactjs.org/docs/react-component.html#updating

If you need a more specific answer (with code), you should explain better what you are trying to achieve.

Upvotes: 2

Related Questions