React Hooks에 대해 읽기 시작했고이를 사용하기 위해 몇 가지 작은 구성 요소를 다시 작성하려고 시도했지만 상태 설정에 문제가 있습니다. 아이 컴퍼넌트 때 기본적으로 <Content/>
항상 반환 false
에 shouldComponentUpdate
, 다음 부모는 ( <App/>.setShow
)가 호출되지만 상태를 업데이트하지 않습니다 및 <Content/>
렌더링되지 않습니다.
아래에서 최소한의 작업 예제를 준비했습니다. 여기서는 <App/>
React Hoos를 기반으로하는 컴포넌트이고 <App2/>
동등한 클래스 기반 컴포넌트입니다. 후자는 작동하므로 분명히 이해하지 못하는 뉘앙스가 있습니다.
const {useState} = React;
class Panel extends React.Component {
shouldComponentUpdate() { return false; }
render() { return (<button onClick={this.props.onClick}>Toggle</button>) }
}
class Content extends React.Component {
render() { return <div>Content</div> }
}
const App = (props) => {
const [show, setShow] = useState(true);
const toggle = () => {
console.log("Toggling visibility!", show);
setShow(!show);
}
console.log("[App] render()");
return (<div >
<h1>Hi at {Date.now()}</h1>
<Panel onClick={toggle} />
{show && <Content /> }
</div>)
}
class App2 extends React.Component {
state = { show: true }
render() {
const toggle = () => {
console.log("[App] toggle", this.state.show)
this.setState({ show: !this.state.show })
}
console.log("[App] render()");
return (<div >
<h1>Hi at {Date.now()}</h1>
<Panel onClick={toggle} />
{this.state.show && <Content />}
</div>)
}
}
ReactDOM.render(<div> <App/> <App2/> </div>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="app">
</app>
내부 기능의 가치에 대한 폐쇄 가 있기 때문에 기능 업데이트 를 사용해야 합니다.show
toggle
클로저 shouldComponentUpdate
는 항상을 반환 하기 때문에 발생하므로 false
처음 렌더링 할 때의 값 this.props.onClick
은의 오래된 상태를 가지므로 show === true
후속 렌더링에서 변경되지 않습니다.
const App = () => {
const [show, setShow] = useState(true);
// Closure on value of show
// const toggle = () => {
// console.log("Toggling visibility!", show);
// setShow(!show);
// }
const toggle = () => {
setShow(prevState => {
console.log("Toggling visibility!", prevState);
return !prevState;
});
};
console.log("[App] render()");
return (
<div>
<h1>Hi at {Date.now()}</h1>
<Panel onClick={toggle} />
{show && <Content />}
</div>
);
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다