反应|承诺在Promise.then()上承诺未取消类型错误



i具有以下方法,该方法检查用户列表中是否存在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;

不确定有什么问题,也许当我拨打电话时,数据不存在,我需要异步 - 瓦特之类的东西。我需要一些帮助。谢谢!

  1. 如注释Array.isArray()中提到的Boolean中所述,您无法在布尔值上调用数组方法,您需要检查data.username是否是数组,然后单独运行它。

  2. 我也认为您应该使用包括contains

  3. 要处理.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)
})