【问题标题】:React | Promise Uncaught Type Error on Promise.then()反应 | Promise.then() 上的 Promise 未捕获类型错误
【发布时间】:2019-08-04 16:12:20
【问题描述】:

我在 React 中有以下方法,它检查 params.data 中的用户名是否存在于用户列表中。如果用户在场,我们将呈现正常的详细信息视图。如果没有,我们会显示 404 页面。

  validateUsername = (match, params) =>
    listUsers().then(({ data }) => {
      if (Array.isArray(data.username).contains(params.username)) {
        return true;
      }
      return false;
    });

这件事奏效了。它有效,魅力,我每次都被重定向到正确的渲染中。但是我得到了这个错误,我正试图消除这个错误,因为我正计划测试这种情况。

这是组件:

import { getUser, listUsers } from '../../config/service';
// The above are the services I use to call specific endpoint,
// They return a promise themselves.

class UserDetailsScreen extends Component {
  static propTypes = {
    match: PropTypes.shape({
      isExact: PropTypes.bool,
      params: PropTypes.object,
      path: PropTypes.string,
      url: PropTypes.string
    }),
    label: PropTypes.string,
    actualValue: PropTypes.string,
    callBack: PropTypes.func
  };

  state = {
    user: {}
  };

  componentDidMount() {
    this.fetchUser();
  }

  getUserUsername = () => {
    const { match } = this.props;
    const { params } = match; // If I print this, it is fine.
    return params.username;
  };

  fetchUser = () => {
    getUser(this.getUserUsername()).then(username => {
      this.setState({
        user: username.data
      });
    });
  };

  validateUsername = (params) =>
    listUsers().then(({ data }) => {
      // Data are printed, just fine. I get
      // the list of users I have on my API.
      if (Array.isArray(data.username).contains(params.username)) {
      // The error is here in params.username. It is undefined.
        return true;
      }
      return false;
    });

  renderNoResourceComponent = () => {
    const { user } = this.state;
    return (
      <div className="center-block" data-test="no-resource-component">
        <NoResource
           ... More content for the no user with that name render
        </NoResource>
      </div>
    );
  };

  render() {
    const { user } = this.state;
    const { callBack, actualValue, label } = this.props;
    return (
      <div className="container-fluid">
        {user && this.validateUsername() ? (
          <Fragment>
            <div className="row">
              ...More content for the normal render here...
            </div>
          </Fragment>
        ) : (
            <div className="container-fluid">
              {this.renderNoResourceComponent()}
            </div>
          )}
      </div>
    );
  }
}

export default UserDetailsScreen;

不知道哪里出了问题,也许我打电话时数据不存在,我需要 async-await 什么的。我需要帮助。谢谢!

【问题讨论】:

  • 它不起作用。 Array.isArray 返回一个布尔值,布尔值没有 .contains 方法(也没有任何其他 JS 值)
  • 好的,所以即使我删除它,它也不会停止抱怨。实际的解决方案是什么?我做错了吗?
  • 那么还有一个错误...
  • user &amp;&amp; this.validateUsername() ? … : … 不起作用。 validateUsername 返回一个永远真实的承诺。
  • 嗯,它报告了什么类型错误?

标签: javascript reactjs async-await es6-promise


【解决方案1】:
    1234563
  1. 我也认为你应该使用includes 而不是contains

  2. 要处理.then 中发生的错误,您可以链接.catch,它接受一个函数作为参数。您提供的函数将收到错误作为参数供您处理。

const examplePromise = new Promise(resolve => {
  const data = {
    username: ['a','b', 'c']
  }

  setTimeout(() => {
    resolve({data});
  }, 1000);
})


examplePromise.then(({data}) => {
  console.log(data.username.contains('a'))
}).catch(err => {
  // VM1025 pen.js:13 Uncaught (in promise) TypeError: data.username.contains is not a function
  console.log(err)
})

examplePromise.then(({data}) => {
  console.log('works', data.username.includes('a'))
}).catch(err => {
  console.log(err)
})

【讨论】:

  • 我已经扩展了我的答案,如果您要投反对票,请解释原因,因为这将帮助我理解我的答案如何无法回答问题。简单地投反对票对任何人都没有帮助。
  • 顺便说一句,我没有对你投反对票。实际上,根据您的答案和我在博客中找到的扩展答案,我设法使错误消失了……我最终还是按照您建议的方式使用了包含,但方式略有不同……将更新几个小时这里已经很晚了...感谢您的努力...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-11
  • 2021-06-29
  • 2016-10-18
  • 1970-01-01
  • 2018-11-09
相关资源
最近更新 更多