首页 > 解决方案 > 第一次 API 调用后如何让 React 更新

问题描述

我成功地进行了第一个 API 调用并获取了数据并进行了渲染。

我想做的事:

状态得到更新(我在控制台中打印了它),但组件在收到它后没有发出新的调用。

完整代码在这里https://stackblitz.com/edit/react-hgg1se?file=index.js

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      news: [],
      category: ''
    }

    this.getCategory = this.getCategory.bind(this)
  }

  componentDidMount() {
    fetch(`https://newsapi.org/v2/top-headlines?country=us&category=`+this.state.category+`&apiKey=2179f689f9224a2993696143ec3e97eb`)
      .then(response => response.json())
      .then(response => {
        console.log(response.articles)
        this.setState({
          news: response.articles
        })

      })
  }
  /* this function gets called after button clicked to update the state */
  getCategory(event) {
    this.setState({ category: event.target.value }, function(){ console.log(this.state.category) } );
  }

  render() {

    return (
      <div>

        <div className='container'>
          <form>
            <div className="form-group">
              <div className='col-sm-12'>
                <input type="text" className="form-control text-primary" placeholder="search" />
              </div>
            </div>
          </form>
          /* here where I get the value of clicked button */
          <button type="button" onClick={this.getCategory} value="Technology" class="btn btn-primary"> Technology </button>
          <button type="button" onClick={this.getCategory} value="Business" class="btn btn-primary"> Business </button>
          <button type="button" onClick={this.getCategory} value="Science" class="btn btn-primary"> Science </button>
          <button type="button" onClick={this.getCategory} value="Entertainment" class="btn btn-primary"> Entertainment </button>
          <button type="button" onClick={this.getCategory} value="Health" class="btn btn-primary"> Health </button>
          <button type="button" onClick={this.getCategory} value="Sports" class="btn btn-primary"> Sports </button>

        </div>

        <div className='container'>
          <ul className="list-group">

            {this.state.news.map((article) =>
              <li className='list-group-item border-left-0 border-right-0'>
                <div className="row">



                  <div className='col-9'>
                    <a href={article.url}>
                      {article.title}
                    </a>
                  </div>


                  <div className="col-3">
                    <a href={article.url} className="thumbnail">
                      <img src={article.urlToImage != 'null' ? article.urlToImage : 'http://www.publicengagement.ac.uk/sites/default/files/styles/content_width/public/hero/large-crowd-of-people-small.jpg'} class="img-fluid" />
                    </a>
                  </div>

                </div>
              </li>
            )}

          </ul>
        </div>

      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

标签: reactjs

解决方案


你不了解 React 组件的生命周期。

阅读本页。https://reactjs.org/docs/react-component.html#the-component-lifecycle

// [Mount]: just Once called. similar constructor.
// constructor -> componentWillMount -> getDerivedStateFromProps -> render -> componentDidMount

// [Update]: calling after mount
// getDerivedStateFromProps -> shouldComponentUpdate -> getDerivedStateFromProps -> getSnapshotBeforeUpdate -> componentDidUpdate

因此你必须改变componentDidMount-> componentDidUpdate

Reactjs 组件生命周期流程 Mount 后更新。


推荐阅读