004|React의 State

1935 단어
JSX에서 모든 구성 요소는 props 속성 외에 state 속성이 있습니다.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.

좋은 웹페이지 즐겨찾기