将异步获取的数据传递给子 props

ala*_*nan 5 javascript ajax state asynchronous reactjs

我正在制作一个应用程序,它从远程源获取一系列新闻项目并将其显示在页面上。

我有端点,并且可以使用控制台日志证明可以成功进行调用$.getJSON()。我将此调用放入父组件中,因为子组件需要使用数据。

但是,当我将此数据传递给子组件时,会出现控制台错误:

Uncaught TypeError: Cannot read property 'headline' of undefined

这是因为 React 甚至在数据传递到组件之前就尝试渲染组件。这让我觉得我应该首先在componentDidMount.

为了解决这个问题,我在子组件上设置了一个方法,如果存在 prop,则返回标题:

getHeadline: function () {
    if(this.props.newsItems){
        return this.props.newsItems.headline
    } else {
        return null
    }
},
Run Code Online (Sandbox Code Playgroud)

这感觉有点令人讨厌。有没有更好的方法,或者我在代码中遗漏了某些内容?

var BigStory = React.createClass({

    getHeadline: function () {
        if(this.props.newsItems){
            return this.props.newsItems.headline
        } else {
            return null
        }
    },

    render: function () {
        console.log('props:', this.props);
        console.log('newsItems:', this.props.newsItems);
        return (
            <div className="big-story col-xs-12">
                <div className="col-sm-5">
                    <h1>{this.getHeadline()}</h1>
                    <p>Placeholder text here for now.</p>
                    <p>time | link</p>
                </div>
                <div className="col-sm-7">
                    <img src="http://placehold.it/320x220" alt=""/>
                </div>
            </div>
        );
    }
});

var Main = React.createClass({

    getInitialState: function () {
        return {
            newsItems: []
        }
    },

    componentDidMount: function () {
        this.getNewsItems();
    },

    getNewsItems: function () {
        $.getJSON('http://www.freecodecamp.com/news/hot', (data) => {
            console.log('data sample:', data[0]);
            this.setState({newsItems: data})
        })
    },

    render: function () {
        return (
            <div className="container">
                <div className="main-content col-sm-12">
                    <div className="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12">
                        <BigStory newsItems={this.state.newsItems[0]}/>
                    </div>
                </div>
            </div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

Eri*_*bar 4

我建议将其留给父级来决定当它处于“加载”状态时要做什么,并保留BigStory为“哑”组件,该组件始终呈现相同的效果,假设它始终会收到有效的newsItem.

在此示例中,我显示了 a <LoadingComponent />,但这可以是您需要的任何内容。这个概念是BigStory不必担心“接收无效数据”的边缘情况。

var Main = React.createClass({
  // ...
  render() {
    const {newsItems} = this.state;
    // You could do this, pass down `loading` explicitly, or maintain in state
    const loading = newsItems.length === 0;
    return (
      <div className="container">
          <div className="main-content col-sm-12">
              <div className="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12">
                  {loading 
                    ? <LoadingComponent />
                    : <BigStory newsItem={newsItems[0]} />  
                  }
              </div>
          </div>
      </div>
    );
  }
});

function BigStory(props) {
  // Render as usual. This will only be used/rendered w/ a valid
  return (
    <div className="big-story col-xs-12">
      <h1>{props.headline}</h1>
      {/* ... */}
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

BigStory另一种解决方案(尽管我推荐一种更像上面的方法)是始终以相同的方式使用该组件,但在没有加载故事时为其提供“占位符故事”。

const placeholderNewsItem = {
  headline: 'Loading...',
  /* ... */
};

var Main = React.createClass({
  // ...
  render() {
    const {newsItems} = this.state;
    // Conditionally pass BigStory a "placeholder" news item (i.e. with headline = 'Loading...')
    const newsItem = newsItems.length === 0
      ? placeholderNewsItem
      : newsItems[0];
    return (
      <div className="container">
          <div className="main-content col-sm-12">
              <div className="left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12">
                  <BigStory newsItem={newsItem} />
              </div>
          </div>
      </div>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)