首页 > 解决方案 > 如何从 .t​​hen 函数中获取数据

问题描述

试图在 then/catch 语句之外阅读。它在 .then 内部工作正常,但在 react html 内部不起作用

class DashboardPage extends Component {
...

  componentDidMount() {
    axios.get('http://localhost:3000/users/me', this.yourConfig)
  .then(function (response) {
    // handle success
    console.log(response.data.name)
    console.log(response.data.email)

  })
 ....


  render() {
    return (
      <div className="App">
     <p>Welcome {this.response.data.name}</p>
     <p>Your email is {this.response.data.email}</p>
      this is your token {this.tokenCookie}

      </div>
    );
  }
}

标签: javascriptreactjsaxios

解决方案


您需要保存response到状态。像这样的东西应该工作:

class DashboardPage extends Component {
    constructor(props) {
        super(props);
        this.state = {response: null};
    }

...

  componentDidMount() {
    axios.get('http://localhost:3000/users/me', this.yourConfig)
    .then((response) => {
      // handle success
      console.log(response.data.name)
      console.log(response.data.email)
      this.setState({ response });
    });
  }
.... 
  render() {
    if (this.state.response == null) {
      return (<div className="App"><p>Response not loaded</p></div>); // Whatever you want to render when there is no response yet
    } else {
      return (
      <div className="App">
        <p>Welcome {this.state.response.data.name}</p>
        <p>Your email is {this.state.response.data.email}</p>
        this is your token {this.tokenCookie}
      </div>
      );
    }
  }

注意:我将函数 ( function (response)) 更改为 ES6 箭头函数,以便this可以使用。您还可以设置一个变量 like并将var that = this其更改为.thisfunction (response)that


推荐阅读