设置组件状态,但在render()方法中未定义this.props.state

时间:2016-04-17 03:31:24

标签: reactjs

我正在我的组件的componentDidMount()方法中发出get请求。我能够成功地发出请求并设置组件的状态。但是,当我尝试在render()方法中访问状态时,它会以未定义的形式返回。我猜这与javascript的异步性质有关,但似乎无法弄清楚如何正确设置状态,等待确保状态已经设置,然后将其传递给我的render()方法所以我可以在那里访问它。谢谢。

Game.js(组件文件)

import React, { Component } from 'react';
import { Link } from 'react-router';
import axios from 'axios';

export default class Game extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: []
    };
  }

  getReviews() {
    const _this = this;
    axios.get('/api/reviews')
      .then(function(response) {
        _this.setState({
          data: response.data
        });
        console.log(_this.state.data); // shows that this is an array of objects.
      })
      .catch(function(response) {
        console.log(response);
      });
  }

  componentDidMount() {
    this.getReviews();
  }


  render() {

    const allReviews = this.props.data.map((review) => {
       return (
         <li>{review.username}</li>
       );
    })

    console.log(this.props.data); // comes in as undefined here.

    return (
      <div>
        {allReviews}
      </div>
    );
  }
}

0 个答案:

没有答案