004|React의 State
예를 들어, 다음 코드에서는 constructor에서 state를 초기화한 다음render에서 state를 참조합니다.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}; //
}
render() {
return (
Hello, world!
It is {this.state.date.toLocaleTimeString()}.
//
);
}
}
state에서 주의해야 할 요점이 있습니다.우선state 대상을 직접 수정하지 말고 setState 방법을 통해 수정하십시오.state 대상을 직접 수정하면 다시 그리기를 터치하지 않습니다.
// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});
성능을 위해 React는 여러 개의 setState를 하나의 setState 호출로 통합할 수 있습니다.이로 인해 state, props가 비동기적이어서 다음 호출 오류가 발생합니다.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
setState의 함수 모드를 사용하면 다음과 같은 문제를 해결할 수 있습니다.
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
State의 1단계 속성은 setState를 통해 개별적으로 업데이트할 수 있습니다. 예를 들어,
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
this.setState({
posts: response.posts
}); // posts , comments
}
구성 요소 로드 및 언로드
componentDidMount 방법이 실행되면 구성 요소가 불러올 때 이 방법이 호출됩니다.
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
component Will Unmount 방법이 구현되면 어셈블리가 제거될 때 이 방법이 호출됩니다.
componentWillUnmount() {
clearInterval(this.timerID);
}
구성 요소에서 이벤트를 어떻게 처리합니까?
자, 이 절은 여기까지입니다.이후에 나는 점차적으로 React 기술의 세부 사항을 소개하여 상술한 문제를 천천히 해답할 것이다.
컴퓨터 기술을 배우고 싶습니까?1 대 1 전문급 지도교사가 필요합니까?팀워크가 같이 발전하고 싶어요?나를 친구로 추가한 것을 환영합니다!위챗 번호: iTekka.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.