简体   繁体   中英

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>     
    )
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM