简体   繁体   English

State 已更改,但组件未重新加载

[英]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.我有一个按钮刷新女巫应该在组件中更改 state 并且它应该重新渲染它的子组件练习。 The state changes, I can see in console.log, but why there's no rerendering of chd Component? state 发生了变化,我可以在 console.log 中看到,但是为什么没有重新渲染 chd 组件? (if you put smth in input and click Refesh, nothing happens) (如果您将 smth 放入输入并单击刷新,则没有任何反应)

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.当您更改父组件中的 state 时,子组件会重新渲染,但不会破坏它,因此值会保留在那里。

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 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.如果您需要更具体的答案(使用代码),您应该更好地解释您想要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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