繁体   English   中英

反应| Promise.then()上的Promise Uncaught类型错误

[英]React | Promise Uncaught Type Error on Promise.then()

我在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之类的东西。 我需要协助。 谢谢!

  1. 如注释中所述, Array.isArray()返回为布尔值,并且您不能对布尔值调用数组方法,您需要检查data.username是否为数组,然后在其上单独运行方法。

  2. 我也认为您应该使用包含而不是contains

  3. 要处理.catch中发生的错误.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)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM