Javascript 反应:Can';不承诺

Javascript 反应:Can';不承诺,javascript,reactjs,promise,Javascript,Reactjs,Promise,我对此感到非常困惑。在验证JWT后,我试图将isAuthenticated状态设置为true,但它无法工作。控制台日志输出奇怪的东西(下面的屏幕截图) 我怀疑我把fetch承诺搞砸了,但我不知道是什么 class App extends React.Component { constructor(){ super() this.state = { isAuthenticated: false } }

我对此感到非常困惑。在验证JWT后,我试图将
isAuthenticated
状态设置为
true
,但它无法工作。控制台日志输出奇怪的东西(下面的屏幕截图)

我怀疑我把
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);
        });
    }
控制台记录:


React不会自动将
绑定到类方法

你有两种方法来处理这个问题

论构造器

  constructor(){
        super()
        this.state = {
            isAuthenticated: false
        }
        this.authenticate = this.authenticate.bind(this)
    }
或者稍微清洁一下ES6方式,并使用箭头功能

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

console.log(this.state)
是一个同步函数调用-您正在调用它并将
undefined
传递给
setState
的第二个参数-您打算执行
()=>console.log(this.state)
。这就是为什么当您对中的对象状态感兴趣时,我建议使用TypeScript:Duse
console.table
而不是
console.log
time@BenjaminGruenbaum点燃。所以setState实际上是起作用的。非常感谢。我可能应该询问在承诺解决后如何呈现组件,因为我无法让组件使用
isAuthenticated
值。@Babevski React将在每次设置状态后自动重新呈现组件(除非您告诉它不要使用shouldComponentUpdate)