【问题标题】:Why do I get a TypeError: this.getToken is not a function - React JS为什么我会收到 TypeError:this.getToken is not a function - React JS
【发布时间】:2018-10-28 06:51:12
【问题描述】:

我创建了一个使用 json API 的登录页面。登录页面在成功验证后生成一个令牌,并将用户引导到一个由三个下拉框组成的页面。在只关注其中一个下拉框时,我试图让下拉框根据其令牌显示客户端的用户名。

登录页面从另一个对用户进行身份验证的 React JS 页面调用一个函数。

功能:

getToken() {
        // Retrieves the user token from localStorage
        return localStorage.getItem('id_token')
    }

在包含下拉框的登录页面中,我有以下代码:

   componentDidMount() {
        fetch('http://theClientAPI:1111/api/clients', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': `Bearer ${this.getToken()}`
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }

在 render() 部分,我有以下内容:

 <div>
        <select className="custom-select" id="clientName">
                { this.state.data.map(item =>(
                <option key={item.clientName}>{item.clientName}</option>
                ))
                }
            </select>
        </div>

错误出现在我的 Fetch 的这一行:

'Authorization': `Bearer ${this.getToken()}`

我可以就我做错了什么寻求帮助吗?如果您需要更多信息,请告诉我。我在下面发布了登录和身份验证页面背后的代码:

登录页面:https://codepen.io/lkennedy009/pen/GdYOYe?editors=0010#0 认证服务页面:https://codepen.io/lkennedy009/pen/xjyPMY

【问题讨论】:

  • this.getTokens() 应该返回什么。还有什么错误显示?
  • 尝试通过这种方式调用函数${this.getToken.bind(this)}

标签: javascript json reactjs api


【解决方案1】:

您的代码可能存在一些错误。

  1. 在构造函数中绑定函数是一种常见的良好做法,这样可以避免您可能遇到的任何其他错误

    constructor(props) {
        super(props);
    
        // This binding is necessary to make `this` work in the callback
        this.getToken = this.getToken.bind(this);
    }
    
  2. 而不是像这样调用你的函数

    'Authorization': `Bearer ${this.getToken()}`
    

    总是尝试将它定义为一个常量,它有助于调试,这是一个很好的做法,因为函数可能会变得复杂,并且制作更小的组件/模式是 React 有用的原因 - 所以你应该这样做。所以代替上面的例子试试这样的:

    const bearerToken = this.getToken();
    //check if you even get what you expect
    console.log(bearerToken);
    ...
    'Authorization': `Bearer ${bearerToken}`
    
  3. 最后,这些是我将尝试使您的代码正常工作的更改:

    constructor(props) {
        super(props);
    
        this.getToken = this.getToken.bind(this);
    }
    
    componentDidMount() {
        const bearerToken = this.getToken();
    
        fetch('http://theClientAPI:1111/api/clients', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': `Bearer ${bearerToken}`
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }
    
    getToken() {
        return localStorage.getItem('id_token'); 
    }
    

我在 componentDidMount 之后定义 getToken 的原因是因为 AirBnB 的 JavaScript ESlint 规则,如果它是在 componentDidMount 或其他保留的 React 函数(生命周期和其他)之上定义的,则会引发警告

【讨论】:

  • 谢谢,您提供的建议和示例代码非常有帮助,尤其是对于像我这样刚接触 React JS 的人。
猜你喜欢
  • 2020-09-13
  • 2022-06-22
  • 1970-01-01
  • 2021-11-20
  • 2013-07-12
  • 1970-01-01
  • 2015-08-10
  • 2020-01-20
  • 2019-05-08
相关资源
最近更新 更多