質問

I was going through the react getting started tutorial and have run into a problem with an experiment I am doing. I am able log an object but in the console, I get the following error:

Uncaught TypeError: Cannot read property 'results' of undefined

I can log the object so I know my api call is successfully but for some reason my react state does not seem to get updated. I think that my render function is happening before my data object gets updated from the API but not sure how to fix it.

http://jsfiddle.net/xJvY5/

<!doctype html>
<html>
<head>
    <title>Weather Widget</title>
    <link rel="stylesheet" href="weather.css" />
    <script src="http://fb.me/react-0.10.0.js"></script>
    <script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/jsx">
    /*** @jsx React.DOM */
    var weatherWidget = React.createClass({
        loadData: function(){
            $.ajax({
                url: 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%2222102%22&format=json',
                dataType : "jsonp",
                cache: false,
                success: function(data) {
                    console.log(data)
                    this.setState({data: data});
              }.bind(this)
            });
        },
        getInitialState: function(){
            return {data: []};
        },
        componentWillMount: function(){
            this.loadData();
        },
        render: function(){
            return(
                <div className="ww-container">
                    <div className="ww-current-condition">
                        <div className="ww-current-temperture">{this.state.data.query.results.channel.item.condition.temp}&deg;</div>
                    </div>
                </div>
            )
        }
    });

    React.renderComponent(<weatherWidget />, document.body);
</script>
</body>

</html>
役に立ちましたか?

解決

The problem is that React is trying to access the result of the API call while it hasn't been fetched yet. You should add null checks when accessing nested objects (this is a javascript issue rather than something React-specific).

Secondly, while the data is unavailable, your component will still try to render something. React renders your component the moment you inject it into the page, so consider showing a "loading" indicator while the API result has not been saved to state.

Here is a fork of your fiddle with appropriate null checks & "loading indicator":

http://jsfiddle.net/jxg/9WZA5/

render: function(){
  var degrees = this.state.item ? this.state.item.condition.temp : 'loading...';
  return(
    <div className="ww-container">
      <div className="ww-current-condition">
        <div className="ww-current-temperture">{degrees}&deg;</div>
      </div>
    </div>
  );
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top