简体   繁体   English

在React中的组件之间传递数据

[英]Passing data between components in React

Ultimately I'm trying to pass mapped elements in an array to a child component. 最终,我试图将数组中的映射元素传递给子组件。 I made a WordPress API call to get back posts for a preview page, and now that I'm trying to have that data render in their own pages, I keep getting that the data is undefined. 我进行了WordPress API调用,以获取预览页面的帖子,现在,我试图将数据呈现在自己的页面中,但我一直在获取未定义的数据。 The dynamic links are rendering as expected, but none of the other data is being passed. 动态链接正在按预期方式呈现,但其他任何数据均未传递。

Articles.js Articles.js

// cut for brevity
  render() {

    let articles = this.state.newsData.map((article, index) => {
      if(this.state.requestFailed) return <p>Failed!</p>
      if(!this.state.newsData) return <p>Loading...</p> 
      return(
        <div key={index} className="article-container">

          <div className="article-preview">
          <span className="article-date">{article.date}</span>
          <h5>{article.title.rendered}</h5>
          <div dangerouslySetInnerHTML={{ __html: article.excerpt.rendered }} />

          <Link to={`/news/${article.slug}`}>Read More...</Link>

          </div>
          <Route path={`/news/:articleSlug`}
            render={ props => <Article data={article} {...props} />} 
            />
        </div>

      )
    });

    return (
      <div>
        <h3>All Articles from Blog</h3>
        {articles}
      </div>
    )
  }

Article.js Article.js

import React from 'react';

const Article = ({match, data}) => {
  let articleData;
  { console.log(this.data) }

  if(data)
    articleData = <div>
      <h3> {data.title.rendered}</h3>
      <div dangerouslySetInnerHTML={{ __html: data.content.rendered }} />
      <hr />
    </div>

  else 
    articleData = <h2> Sorry. That article doesn't exist. </h2>;

    return (
      <div>
        <div>
          {articleData}
        </div>
      </div>
    )
}

export default Article;

How do I get the data from the array into the Article component? 如何将数组中的数据获取到Article组件中?

Your problem is with asynchronous requests. 您的问题是异步请求。

You have a route that will call the render method when the user clicks on a link. 您有一条route ,当用户单击链接时,该route将调用render方法。 At that point in time, javascript has no reference to the article anymore, you need to persist it. 到那时,javascript不再引用该article了,您需要坚持下去。

Here's an example of what you are experiencing 这是您正在经历的一个例子

 for (var i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 1); } 

The code above will always log 10 上面的代码将始终记录10

A solution to this problem is using bind . 解决此问题的方法是使用bind

 for (var i = 0; i < 10; i++) { setTimeout(function(i) { console.log(i); }.bind(null, i), 1); } 

So, in your code, you need to persist the article variable. 因此,在您的代码中,您需要保留article变量。

You can do that by calling a method that takes the data . 您可以通过调用获取data的方法来做到这一点。

  renderArticle(data) {
    return props => <Article data={data} {...props} />
  }

  render() {

    let articles = this.state.newsData.map((article, index) => {
      if(this.state.requestFailed) return <p>Failed!</p>
      if(!this.state.newsData) return <p>Loading...</p> 
      return(
        <div key={index} className="article-container">

          <div className="article-preview">
          <span className="article-date">{article.date}</span>
          <h5>{article.title.rendered}</h5>
          <div dangerouslySetInnerHTML={{ __html: article.excerpt.rendered }} />

          <Link to={`/news/${article.slug}`}>Read More...</Link>

          </div>
          <Route path={`/news/:articleSlug`}
            render={this.renderArticle(article)} 
            />
        </div>

      )
    });

    return (
      <div>
        <h3>All Articles from Blog</h3>
        {articles}
      </div>
    )
  }

Hope this points you in the right direction. 希望这能为您指明正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM