簡體   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