간단한 reactJS 클래스에서 this.setState()는 실제로 상태를 설정하지 않았습니다. 비동기 적으로 호출된다는 것을 알고 있지만 구성 요소가 다시 렌더링 될 때도 상태는 변경되지 않았습니다. 그래서 this.state.showModal
은이고 구성 요소가 마운트 될 때 (예상대로) true
"영원히"입니다.setTimeout에서 setState를 호출 할 때 ReactJS가 상태를 설정하는 이유는 무엇입니까?
setTimeout(() => this.setState({ showModal: false }), 0)
hideModal
기능을 교체 할 때
class Modal extends Component {
render() {
return (
<div className='configurator-modal'>
<button className='close' onClick={this.props.close}> x </button>
Modal
</div>
)
}
}
그러나, 상기 모달 구성 요소
class MyComponent extends Component {
constructor (props) {
super(props)
this.state = {
showModal: false
}
this.showModal = this.showModal.bind(this)
this.hideModal = this.hideModal.bind(this)
}
showModal() {
this.setState({ showModal: true })
}
hideModal() {
this.setState({ showModal: false })
}
render() {
console.log(this.state.showModal) // Outputs true even after the hideModal() call
return (
<Components>
<div onClick={this.showModal}>
{
this.state.showModal === true
? <Modal
handles={handles}
close={this.hideModal}
/>
: '+'
}
</div>
</Components>
)
}
}
여기
입니다 : 여기
은 간단한 예제상태가 변형되어 렌더됩니다. d.
왜 ReactJS가 내부적으로 상태를 재설정하거나 상태가 변이되지 않도록 할 수 있는지 궁금합니다.
편집 : hideModal에 호출하고 showModal는 어느 showModal
를 호출하고 true로 상태를 변경 너무 당신은 부모 요소에 click
핸들러가
'hidemodal'을 어떻게 호출해야하는지 보여줄 필요가 있습니까? – Panther
'hideModal' 메서드를 어떻게 호출하는지 알려줄 수 있습니까? – vs1682
내 게시물을 편집했습니다. 죄송합니다. 코드를 너무 단순화하려고했습니다. – 3Dos