【发布时间】:2018-12-16 20:05:03
【问题描述】:
我是超级新手,我一直在努力找出导致chrome console 中此错误的原因
bundle.js:15316 Uncaught (in promise) TypeError: _this2.setState is not a function
我正在尝试使用 facebook 对 web 应用进行简单的登录,以了解登录流程。
我已经在/(也是我的home 页面路由)上设置了我的登录名。我不认为问题出在路由或其他任何地方。这似乎是 react 中的 binding 的问题,并且是这个框架的新手 - 我很难弄清楚如何解决这个问题。
我的/ 或home 路由jsx 看起来像这样
import React, { Component } from "react";
import { browserHistory } from 'react-router';
import FacebookLogin from 'react-facebook-login';
export default class Home extends Component {
constructor() {
super();
this.state = { isAuthenticated: false, user: null, token: ''};
this.setInputState = this.setInputState.bind(this);
}
/*logout = () => {
this.setState({isAuthenticated: false, token: '', user: null})
};*/
responseFacebook(response) {
console.log(response)
const accessTokenBlob = new Blob([JSON.stringify({input_token: response.accessToken}, null, 2)], {type : 'application/json'});
const options = {
method: 'POST',
body: accessTokenBlob,
//mode: 'cors',
cache: 'default'
};
fetch('http://localhost:8880/auth/facebook', options)
.then((r) => r.json())
.then(r => {
console.log(r)
if (r.status) {
this.setState({isAuthenticated: true, user: response.id, token: response.accessToken})
}
});
}
componentDidMount() {
browserHistory.push('/');
}
render() {
console.log(this.state)
let content = this.state.isAuthenticated ?
(
<div>
<p>Authenticated</p>
<div>
{this.state.user.name}
</div>
<div>
<button onClick={this.logout} className="button">
Log out
</button>
</div>
</div>
) : (
<div>
<FacebookLogin
appId="2128489194096154"
autoLoad={true}
fields="name,id,picture"
scope="public_profile"
callback={this.responseFacebook} />
</div>
);
return (
<div className="App">
{content}
</div>
);
}
}
问题似乎发生在包含这部分代码 this.setState({isAuthenticated: true, user: response.id, token: response.accessToken})
当我在浏览器的控制台上设置debug 时,我看到这是this2 错误堆栈链接中的替换内容:
fetch('http://localhost:8880/auth/facebook', options).then(function (r) {
return r.json();
}).then(function (r) {
console.log(r);
if (r.status) {
_this2.setState({ isAuthenticated: true, user: response.id, token: response.accessToken });
}
});
我已经在这个问题上待了将近一天,我完全迷失了 - 已经阅读了几篇文章 - 并且没有得到任何结果。当我一直在努力解决这个问题时,如果问题不清楚 - 请让我知道我可以添加哪些更多细节。
编辑#1
http://localhost:8880/auth/facebook 这是我写的后端,这是我控制的。后端的响应日志和前端收到的数据是一样的。这告诉我cors 或其他集成问题没有问题。
【问题讨论】:
-
像这样使用箭头函数
responseFacebook = (response) => { -
在线包含这个
callback={this.responseFacebook} />也绑定responsefacebook函数。 -
感谢@PrakashSharma - 您的解决方案似乎对我有用。
标签: javascript reactjs react-native react-router react-redux