programing

React 클래스 구성 요소에서 작업 전후의 로드 상태 설정

lovejava 2023. 2. 23. 21:56

React 클래스 구성 요소에서 작업 전후의 로드 상태 설정

액션을 디스패치하는 기능이 있습니다.작업 전후에 로더를 표시하고 싶습니다.오브젝트를 구성하는 리액션이 전달되는 것을 알고 있습니다.setState문제는 어떻게 비동기 방식으로 속성을 갱신할 수 있느냐입니다.

handleChange(input) {
    this.setState({ load: true })
    this.props.actions.getItemsFromThirtParty(input)
    this.setState({ load: false })
}

기본적으로 이 속성을 애플리케이션 상태(Redux 사용)의 일부로 설정하면 모든 것이 잘 작동하지만, 이 속성을 구성 요소 상태로만 전환하는 것이 좋습니다.

다음과 같이 setState를 Promise로 랩하고 비동기/대기 기능을 사용할 수 있습니다.

setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve)
    });
}

async handleChange(input) {
    await this.setStateAsync({ load: true });
    this.props.actions.getItemsFromThirtParty(input);
    await this.setStateAsync({ load: false })
}

출처: ASynC WAIT With RECT

첫 번째 콜백에 나머지 코드를 랩합니다.setState:

handleChange(input) {
  this.setState({
    load: true
  }, () => {
    this.props.actions.getItemsFromThirtParty(input)
    this.setState({ load: false })
  })
}

이것으로, 당신의load로 설정되어 있는 것이 보증됩니다.true전에getItemsFromThirtParty호출되어load로 되돌아가다false.

이것은, 다음의 것을 전제로 하고 있습니다.getItemsFromThirtParty함수는 동기화되어 있습니다.그렇지 않으면 약속으로 바꿔서 결승에 전화하세요.setState쇠사슬에 묶여서then()방법:

handleChange(input) {
  this.setState({
    load: true
  }, () => {
    this.props.actions.getItemsFromThirtParty(input)
      .then(() => {
        this.setState({ load: false })
      })
  })
}

다음은 "async-ait" setState의 타이프스크립트 구현입니다.

async function setStateAsync<P, S, K extends keyof S>(
  component: Component<P, S>,
  state:
    ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) |
    Pick<S, K> |
    S |
    null
) {
  return new Promise(resolve => component.setState(state, resolve));
}

이전 답변은 Hooks에서 사용할 수 없습니다.이 경우 두 번째 인수를 전달하면 다음 오류가 발생합니다.setState

경고: useState() 및 useReducer() 후크로부터의 상태 갱신은 두 번째 콜백 인수를 지원하지 않습니다.렌더링 후 부작용을 실행하려면 useEffect()를 사용하여 컴포넌트 본문에 선언합니다.

에러 메세지에 나타나 있듯이,useEffect대신 이 경우(자세한 내용은 이 설명도 참조)

당신이 할 수 있는 일은...

  1. 액션을 변경하여onFetchComplete콜백, 와 함께input.
  2. 핸들을 변경합니다.변경처:

    handleChange(input) {
        this.setState({ load: true }, ()=>
            this.props.actions.getItemsFromThirtParty(input,
            ()=>this.setState({ load: false }))
        );
    }
    

이렇게 하면 액션프로세서 코드가 약속 기반 방식이 아니더라도 상태 변경 콜백을 호출할 수 있습니다.

액션 크리에이터와 비동기/대기자를 위한 작은 업데이트는 매우 효과적이며, "그때" 체인(chaining)에 비해 코드를 더욱 깔끔하게 만듭니다.

(async () => {
   try {
    await this.props.actions.async1(this.state.data1);
    await this.props.actions.async2(this.state.data2) 
    this.setState({ load: false );
   } catch (e) {
    this.setState({load: false, notify: "error"});
   }
})();

물론 그것은 취향의 문제이다.

EDIT : 누락된 괄호 추가

수업 구성 요소 때문인 건 알지만...다만, 기능 컴포넌트에서는, 상태를 동기적으로 설정하기 위해서 다음과 같이 실시합니다.

const handleUpdateCountry(newCountry) {
    setLoad(() => true);
    setCompanyLocation(() => newCountry);
    setLoad(() => false);
}

국가 자동 탐지 양식을 더럽게 설정해 놨어요

다른 답변에서는 언급되지 않은 접근법 중 하나는 set Timeout으로 작업을 래핑하는 것입니다.이것은 후크를 사용하는 경우에도 동작합니다.

예:

handleChange(input) {
    this.setState({ load: true })
    setTimeout(() => {
        this.props.actions.getItemsFromThirtParty(input).finally(() => {
            this.setState({ load: false })
        });
    });
}

언급URL : https://stackoverflow.com/questions/43370176/set-loading-state-before-and-after-an-action-in-a-react-class-component