javascript - 如何从 .t​​hen 函数中获取数据

标签 javascript reactjs axios

尝试读取 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>
    );
  }
}

最佳答案

您需要将响应保存到状态。像这样的东西应该有效:

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。您还可以设置像 var that = this 这样的变量,并将 function (response) 中的 this 更改为 that

关于javascript - 如何从 .t​​hen 函数中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976581/

相关文章:

javascript - 如何不使用 Redux 传递 props?

javascript - 使用 Axios 时出错,但在 Postman 中响应正确

javascript - 如何在父div中插入其他元素后动态更新子div宽度

javascript - 与 python-shell 和 node.js 的双向通信

javascript - 正在寻找一种使用 Google Apps 脚本或 DOCS API 向 Google 文档中的段落添加边框的方法?

javascript - 条件渲染不显示 - ReactJS

javascript - Kinect V2 javascript 关节对象为空

javascript - 在 React 中更新父级中的状态时如何更新子级中的 props?

javascript - 使用 axios 的异步等待不返回错误

javascript - 为什么我仍然收到 api get 请求的 401(未经授权)错误?