简体   繁体   English

如何使用ReactJS更新内容

[英]How to Update content using ReactJS

I'm new in React and I trying to build a simple list of items clickable to get data and update the DOM, I have a list of links on render() 我是React的新手,我试图构建一个可单击的项目的简单列表,以获取数据并更新DOM,我有一个render()上的链接列表

 const listNews = this.state.news.map((item, i) => 
        <ListGroupItem  key={i} className="font-size-1 text-left">
            <a href='#' onClick={() => this.getInfoNews(i)}>{item.title}</a>
        </ListGroupItem>  
  );

the function "getInfoNews(i)" have this piece of code to display the data into DOM 函数“ getInfoNews(i)”具有这段代码,用于将数据显示到DOM中

getInfoNews(i){
    var content = {
        news : this.state.news[i]
      }

      console.log(content.news)

  if(content.news === undefined){
      return (
          <Card>
              <CardBody>
                  <CardTitle>Card Title</CardTitle>
                  <CardSubtitle>Card subtitle</CardSubtitle>
                  <CardText>Some quick example text to build on the card title and card's content.</CardText>               
              </CardBody>
          </Card>
        )
  }else{
       return (
          <Card>
            <CardBody>
                <div className="container">
                    <img src={content.news.urlToImage} className="w-100" />
                    <CardTitle>
                      <div className="bottom-left font-size-2 bg-dark w-50 p-2 text-uppercase text-left">{content.news.title}</div>
                    </CardTitle> 
                </div>
                <CardSubtitle className="text-right text-dark font-size-1 mr-4">
                    by {content.news.author ? content.news.author : "Anonymous"} , published at {content.news.publishedAt}
                </CardSubtitle>
                <CardText className="text-dark font-size-2 mt-4">
                  {content.news.description} <a href={content.news.url} target="_blank">read more</a> 
                </CardText>
            </CardBody>
          </Card>
        )
  }

}

Work perfect on load first time, but dont work once clicked on every link, the data is loaded but the DOM dont update, some one can help me ? 第一次加载时工作完美,但是一旦单击每个链接就不工作,数据已加载但DOM不更新,有人可以帮助我吗? thanks! 谢谢!

React re-renders whenever there is an update to either the state or the props . 反应重新呈现每当有一个更新任一stateprops

For example, you can load new data from API, and then do this.setState to update the component state . 例如,您可以从API加载新数据,然后执行this.setState以更新组件state Then, react will re-render the component automatically. 然后,react将自动重新渲染组件。

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

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