反应状态未设置

时间:2020-04-18 02:09:14

标签: javascript reactjs

这套代码似乎没有更新我的状态,我不确定为什么! api是100%发送回TRUE(从axios console.log看到)。谢谢高级的帮助!

import React, { Component } from 'react';

import axios from 'axios';

export class Test extends Component {
state = {
    reponse: false
}

componentDidMount () {
    axios.get(`/api`)
        .then(res => {
            console.log(res.data.success);
            this.setState({ response: res.data.success });
        });
  }

render() {
    if (this.state.reponse) {
        return (
            <div>
                <h1>Response Gathered!</h1>
            </div>
        )
    } else {
        return (
            <div>
                <button onClick={() => console.log(this.state.reponse)}>Check State</button>
            </div>
        )
    }
}
}

export default Test;

3 个答案:

答案 0 :(得分:2)

更改

state = {
    reponse: false
}

收件人

  state = {
    response: false
 }

状态声明中有一个错字(对re s 响应的响应)。

修改后的代码如下,

class Test extends React.Component {
  state = {
    response: false
  };

  componentDidMount() {
    axios.get(`/api`)
    .then(res => {
        console.log(res.data.success);
        this.setState({ response: res.data.success });
    });
  }

  render() {
    if (this.state.response) {
      return (
        <div>
          <h1>Response Gathered!</h1>
        </div>
      );
    } else {
      return (
        <div>
          <button onClick={() => console.log(this.state.response)}>
            Check State
          </button>
        </div>
      );
    }
  }
}

export default Test;

Working Codesandbox example

答案 1 :(得分:0)

在构造函数中定义def after_sign_in_path_for(resource) root_path :protocol => 'http://' end

state

顺便说一句,有一个拼写错误。

答案 2 :(得分:0)

render() {
    return (
        {this.state.response ? 
          <h1>Some text</h1> : 
          (<div>
              <button onClick={() => console.log(this.state.response)}>
                 Check State
               </button>
           </div>)
        }
    );
  }