【问题标题】:Possible Unhandled Promise Rejection (id:0) TypeError: undefined is not an object可能未处理的 Promise Rejection (id:0) TypeError: undefined is not an object
【发布时间】:2019-06-06 05:49:40
【问题描述】:

我正在尝试在 react native 项目 (android) 中使用 redux、thunk 和导航库来实现登录逻辑,但我得到了未处理的承诺拒绝 (id:0): (evalualting '_this.props.navigation') 知道是什么导致了这个问题或出路吗?

class AuthLoadingScreen extends React.Component {
  constructor() {
    super();
    this._bootstrapAsync();
  }

  _bootstrapAsync = async () => {
      this.props.getUserToken().then(() => {
        this.props.navigation.navigate(this.props.token.token !== null ? Devices' : 'UserAuth');
      }).catch(err => {
          this.setState({ err })
      })

  };

  render() {
    return (
      <View>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

// actionCreator.js
export const getUserToken = () => dispatch =>
 AsyncStorage.getItem('userToken')
        .then((data) => {
            dispatch(loading(false));
            dispatch(getToken(data));
        })
        .catch((err) => {
            dispatch(loading(false));
            dispatch(error(err.message || 'ERROR'));
        })

【问题讨论】:

    标签: react-native react-redux react-native-navigation dispatch-async


    【解决方案1】:

    你在打电话 this._bootstrapAsync() 里面的构造函数把它放在componentDidMount

    class AuthLoadingScreen extends React.Component {
      constructor() {
        super();
    
      }
    
    componentDidMount() {
      this._bootstrapAsync();
    }
    
    ....
    }
    

    【讨论】:

    • 这解决了问题。谢谢
    • 如果它有效,请您接受答案。谢谢
    【解决方案2】:

    动作道具不返回承诺。

    另外,我建议您在react-navigation-redux-helpers 的帮助下调用操作内的导航。

    在操作中使用导航。

    export const getUserToken = () => dispatch => {
       AsyncStorage.getItem('userToken')
            .then((data) => {
                dispatch(loading(false));
                dispatch(getToken(data));
                dispatch(NavigationActions.navigate('successRoute'))
            })
            .catch((err) => {
                dispatch(loading(false));
                dispatch(error(err.message || 'ERROR'));
                dispatch(NavigationActions.navigate('failRoute'))
            });
    }
    

    返回一个派送承诺不是一个好习惯。

    【讨论】:

    • 您介意解释一下为什么返回发送承诺不是一个好的做法吗??
    • 我个人的看法是,除非你需要一个在动作范围内无法完成的完成事件的逻辑,否则你需要一个承诺。这里的导航可以通过 dispatch 来完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多