programing

_이2로 반응하다.setState가 함수가 아님 - 바인딩 문제 발생 가능

prostudy 2022. 3. 21. 09:06
반응형

_이2로 반응하다.setState가 함수가 아님 - 바인딩 문제 발생 가능

나는 아주 새로운 반응을 보이고 있고, 무엇이 이 오류를 일으키는지를 알아내기 위해 애쓰고 있다.chrome console

bundle.js:15316 Uncaught (in promise) TypeError: _this2.setState is not a function

나는 로그인 흐름을 배우기 위해 웹앱에 페이스북으로 간단한 로그인을 하려고 한다.

로그인을 설정했다./(또한 나의home페이지 이동 경로).내 생각에 문제는 라우팅이나 그 무엇과도 관련이 없는 것 같아.이것은 에 문제가 있는 것 같다.bindingreact그리고 이 틀에 익숙하지 않다 - 나는 이것을 어떻게 해결해야 할지 고민 중이다.

나의/또는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기능이 에 구속되지 않다class문맥의그렇게this안쪽에responseFacebook함수가 다음을 참조하지 않음class이렇게 화살표 기능을 사용할 수 있다.

responseFacebook = (response) => {

아니면 명시적으로 할 수 있다.bind의 기능.constructor이것처럼.

    constructor() {
        super();
        this.state = { isAuthenticated: false, user: null, token: ''};
        this.setInputState = this.setInputState.bind(this);
        this.responseFacebook = this.responseFacebook.bind(this);
    }

참조URL: https://stackoverflow.com/questions/51240450/react-this2-setstate-is-not-a-function-possible-binding-issue

반응형