Компонент react-redux не загружается при первом вызове API

#reactjs #redux #react-redux

#reactjs #redux #react-redux

Вопрос:

Я столкнулся с проблемой в react-redux, когда я перехожу к компоненту, который выходит из строя при первом вызове API, после обновления страницы он работает отлично.

   componentDidMount() {
    this.props.getCurrentUser();
    bsCustomFileInput.init();
    if (this.props.response.response) {
      this.setState({
        firstName: this.props.response.response.firstName,
        lastName: this.props.response.response.lastName,
        slug: this.props.response.response.slug,
        email: this.props.response.response.email,
        phoneNumber: this.props.response.response.phoneNumber,
        address: this.props.response.response.address,
        zipcode: this.props.response.response.zipcode,
        aboutYourself: this.props.response.response.aboutYourself
      });
    }
    this.props.updateMyProfileStart();
  }
.........
const mapDispatchToProps = dispatch => {
  return {
    getCurrentUser: () => dispatch(actions.getCurrentUser()),
    onUpdateMyProfile: userData =>
      dispatch(actions.updateMyProfileSuccess(userData)),
    updateMyProfileStart: () => dispatch(actions.updateMyProfileStart())
  };
};

 

Я использую redux-persist для поддержания состояния.

Журнал ошибок

 ProfileSettings.js:68 Uncaught TypeError: Cannot read property 'response' of null
    at ProfileSettings.componentDidMount (ProfileSettings.js:68)
    at commitLifeCycles (react-dom.development.js:19814)
    at commitLayoutEffects (react-dom.development.js:22803)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at commitRootImpl (react-dom.development.js:22541)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at commitRoot (react-dom.development.js:22381)
    at finishSyncRender (react-dom.development.js:21807)
    at performSyncWorkOnRoot (react-dom.development.js:21793)
    at react-dom.development.js:11089
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
    at workLoop (scheduler.development.js:597)
    at flushWork (scheduler.development.js:552)
 

Комментарии:

1. Возможно, вы могли бы добавить значение к состоянию, которое указывало бы, что пользователь загружается, вместо того, чтобы пытаться получить доступ к данным в состоянии, которое еще не существует. Получите пользователя и состояние загрузки с помощью mapStateToProps, и это сработает

2. @HMR не могли бы вы рассказать об этом подробнее?

3. Примеров много

Ответ №1:

Я не совсем уверен, в чем проблема, потому что я не вижу достаточно вашего кода. Однако для меня это звучит как проблема с обещанием. Возможно, getCurrentUser является асинхронным, и в этом случае он возвращает обещание.

Вы могли бы попробовать:

       componentDidMount() {
        this.props.getCurrentUser()
            .then(() => {
                bsCustomFileInput.init();
                if (this.props.response.response) {
                    this.setState({
                        firstName: this.props.response.response.firstName,
                        lastName: this.props.response.response.lastName,
                        slug: this.props.response.response.slug,
                        email: this.props.response.response.email,
                        phoneNumber: this.props.response.response.phoneNumber,
                        address: this.props.response.response.address,
                        zipcode: this.props.response.response.zipcode,
                        aboutYourself: this.props.response.response.aboutYourself
                    });
                }
                this.props.updateMyProfileStart();
            })

    }