gpt4 book ai didi

javascript - 将组件重新渲染到已渲染的容器无法按预期工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:40 26 4
gpt4 key购买 nike

你能给我解释一下为什么重新渲染的元素没有应用到元素 state.status 属性的更改吗?使用 ReactDOM.unmountComponentAtNode 是正确的方法吗?我知道元素不应该删除自己但这是为了演示。

class CustomModal extends React.Component {

constructor(props){
super(props)
this.state = {

status:this.props.status

}
this.onClick = this.onClick.bind(this);
}


render(){
return <h1 onClick={this.onClick}>Click Me!</h1>
}

onClick(){

console.log('May i log to console?:' + this.state.status)


this.setState({status:false});

// this is somewhat cumbersome?
{/* ReactDOM.unmountComponentAtNode(document.getElementById('container')) */}

// supposed to rerender the element?
// And the state.status element should be true?
ReactDOM.render(<CustomModal status={true} />,document.getElementById('container'))
}

}


ReactDOM.render(<CustomModal status={true} />,document.getElementById('container'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id="container">

</div>

最佳答案

The primary API for rendering into the DOM looks like this:

ReactDOM.render(reactElement, domContainerNode)

To update the properties of an existing component, you call render again with a new element.

If you are rendering React components within a single-page app, you may need to plug into the app's view lifecycle to ensure your app will invoke unmountComponentAtNode at the appropriate time. React will not automatically clean up a tree. You need to manually call:

ReactDOM.unmountComponentAtNode(domContainerNode)

This is important and often forgotten. Forgetting to call unmountComponentAtNode will cause your app to leak memory. There is no way for us to automatically detect when it is appropriate to do this work. Every system is different.

It is not unique to the DOM. If you want to insert a React Native view in the middle of an existing iOS app you will hit similar issues.

来源:https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html

关于javascript - 将组件重新渲染到已渲染的容器无法按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44940207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com