繁体   English   中英

为什么会收到TypeError:this.getToken不是函数-React JS

[英]Why do I get a TypeError: this.getToken is not a function - React JS

我创建了一个使用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>

错误出现在我的提取的这一行:

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

关于我做错了什么,我可以得到一些帮助吗? 如果您需要更多信息,请告诉我。 我将代码张贴在登录名和下面的身份验证页面的后面:

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

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

  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或其他保留的React函数(生命周期等)之上定义了AirBnB针对Javascript的ESlint规则,则我在componentDidMount之后定义getToken的原因将引发警告

暂无
暂无

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

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