IT이야기

Redex 동적 데이터 소스와 상호 작용

cyworld 2022. 3. 12. 10:24
반응형

Redex 동적 데이터 소스와 상호 작용

Udemy와 함께 RN을 배우고 있다. Stephen Grider의 Complete React Native and Redex Course와 나는 Firebase로 매니지먼트 앱을 만들고 있다.

다음에서 연결 기능을 사용할 수 있다.react-redux을 가지고 있다mapStateToProps()그래서 내가 나의 주에 변화가 있을 때마다, 나는 그것들을 내 구성 요소 안에서 소품으로 받을 것이다.

Firebase 데이터베이스에서 데이터를 가져오는 액션을 만들었는데 나중에 호출할 겁니다.componentWillMount()하지만 데이터 가져오기는 비동기 작업이기 때문에componentWillReceiveProps().

하지만 강사는 내가 전화해야 한다고 말했다.createDataSource()둘 다로componentWillMount()그리고componentWillReceiveProps().

왜 그런지 이해할 수 없어!!주(여기 내 직원 명단)에 변화가 있으면 소품으로 받을 테니 전화해도 충분하다고 생각한다.createDataSource()componentWillReceiveProps()단지

누가 그것을 신고해 주시겠습니까?내가 잊어버린 특별한 케이스가 있을까?

갱신하다

직원작업.js:

export const employeesFetch = () => {
  const { currentUser } = firebase.auth();

  return dispatch => {
    firebase
      .database()
      .ref(`/users/${currentUser.uid}/employees`)
      .on("value", snapshot => {
        dispatch({ type: EMPLOYEES_FETCH_SUCCESS, payload: snapshot.val() });
      });
  };
};

직원 목록.js:

  componentWillMount() {
    this.props.employeesFetch();

    this.createDataSource(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.createDataSource(nextProps);
  }

  createDataSource({ employees }) {
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });

    this.dataSource = ds.cloneWithRows(employees);
  }

그래서 나는 사용하고 있다.ListView소방서에서 데려온 내 직원들을 보여주려고!그냥 사용해도 문제가 없을까?createDataSource()에서componentWillReceiveProps()?

나는 또한 네가 말한 Udemi 코스를 수료했고, 우선 componentWillReceiveProp()과 componentWillMount() 소품 사용이 금지되고 있으므로 더 이상 사용해서는 안 된다고 말해야 한다.새 프로젝트에서는 정적 getDearivedStateFromProps() 및 구성 요소DidUpdate()를 사용하는 것이 좋다.공식 리액트 문서는 이 주제에 대한 추가 정보를 제공한다.

그러나 componentWillReceiveProps()는 초기 렌더링이 완료된 후에만 호출되므로 구성 요소가 인스턴스화 시 소품을 수신하지 않으면 componentWillMount()에서 설정을 수행해야 한다.

편집 새로운 모범 사례를 준수하려면 다음과 같이 하십시오.

  • 생성자에서 인스턴스화 수행
  • 비동기 설정을 componentDidMount()로 이동해야 함
  • 정적 getDerivedStateFromProps()가 모든 렌더 앞에 호출됨(업데이트로 인해 초기 렌더링 및 재렌더)
  • componentDidUpdate()는 초기 렌더링 후 소품 업데이트 시 호출됨

나도 같은 우디암 과정을 밟았고 일부 리액션 라이프사이클이 다른 라이프사이클로 대체되고 있다는 글을 읽고 코드를 리팩터링하는 과정에 있었다.

이것이 내가 가지고 업데이트하는 오래된 논리야.

    state = { dataSource: [] }

    componentWillMount() {
      const { userCentres } = this.props;

      this.props.fetchCentres(userCentres);
      this.createDataSource(this.props);
    }

    componentWillReceiveProps(nextProps) {
      this.createDataSource(nextProps);
    }

    createDataSource({ centresList }) {
      this.setState({ dataSource: centresList });
    }

다음을 사용하여 현재 논리를 바꾸려고 시도했다.static getDerivedStateFromProps하지만 나는 키워드를 사용할 수 없어서 문제가 있었다.this내가 전화할 수 없다는 뜻의 범위 안에this.createDataSource(props)그것으로부터나는 또한 "당신은 아마도 파생된 상태가 필요하지 않을 것이다"라고 읽었고, 그 후에 그것을 사용하는 것이 훨씬 더 좋다.getSnapshotBeforeUpdate그리고componentDidUpdate대신에

getSnapshotBeforeUpdate()는 가장 최근에 렌더링된 출력이 DOM에 커밋되기 직전에 호출된다.잠재적으로 변경되기 전에 구성 요소가 DOM(예: 스크롤 위치)에서 일부 정보를 캡처할 수 있도록 한다.이 라이프사이클에 의해 반환되는 값은 componentDidUpdate()에 매개 변수로 전달된다.

내 코드를 리팩터링한 방법이야

      state = { dataSource: [] }

      componentDidMount() {
        const { userCentres } = this.props;

        this.props.fetchCentres(userCentres);
      }

      componentDidUpdate(prevProps, prevState, snapshot) {
        if (snapshot) {
          this.createDataSource(this.props);
        }
      }

      getSnapshotBeforeUpdate(prevProps) {
        if (prevProps.centresList !== this.props.centresList) {
          return true;
        }

        return null;
      }

      createDataSource({ centresList }) {
        this.setState({ dataSource: centresList });
      }

이것이 문제를 해결하는 가장 좋은 방법이라고 100% 확신할 수는 없지만, 이것은 결국 나에게 효과가 있었다.나는 또한 이것이 PureComponent라는 것을 주목해야 한다.

참조URL: https://stackoverflow.com/questions/50703571/react-native-with-redux-dynamic-data-source

반응형