如何从.then函数中获取数据

时间:2019-07-10 18:24:24

标签: javascript reactjs axios

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

{replicate}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您不能在该函数之外使用响应变量 最好的解决方法是使用状态  doc中的示例-> https://reactjs.org/docs/faq-ajax.html

 componentDidMount() {
        fetch("https://api.example.com/items")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: result.items
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }