简体   繁体   English

反应:不能在承诺中设置状态

[英]React: Can't setState in promise

I am very confused about this. 我对此很困惑。 I am trying to set the isAuthenticated state to true after verifying a JWT, and it won't work. 验证JWT后,我尝试将isAuthenticated状态设置为true ,它将无法正常工作。 The console logs are outputting weird things (screenshot below). 控制台日志正在输出奇怪的内容(下面的屏幕截图)。

I suspect I am messing something up with the fetch promise, but I don't know what. 我怀疑我把fetch承诺弄乱了,但我不知道是什么。

class App extends React.Component {
    constructor(){
        super()
        this.state = {
            isAuthenticated: false
        }
    }

    componentWillMount(){
        this.authenticate()
    }

    authenticate(){
        fetch("http://localhost:3000/authenticated", {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                token: localStorage.getItem("token")
            })
        })
        .then(res => res.json())
        .then(data => {
            console.log(data);        // Server returns true
            console.log(this.state);  // isAuthenticated: false
            console.log(this);        // isAuthenticated: true
            if(data.success){
                this.setState({
                    isAuthenticated: true
                }, console.log(this.state))   // isAuthenticated: false
            }
        })
        .catch(err => {
            console.log(err);
        });
    }

The console logs: 控制台日志:

在此处输入图片说明

React doesn't bind automatically this to class methods. React不会自动this绑定到类方法。

You have two ways to handle this. 您有两种方法可以解决此问题。

on constructor 在构造函数上

  constructor(){
        super()
        this.state = {
            isAuthenticated: false
        }
        this.authenticate = this.authenticate.bind(this)
    }

or a bit cleaner ES6 way and use arrow functions 或使用更清洁的ES6方式并使用箭头功能

authenticate = () => {
  [your code]
  this.setState({ isAuthenticated: true }) // example
}

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

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