reactjs - 第一次 API 调用后如何让 React 更新
问题描述
我成功地进行了第一个 API 调用并获取了数据并进行了渲染。
我想做的事:
- 我根据按钮单击更新渲染数据。
这意味着我得到点击按钮的值然后我调用函数getCategory,在调用函数后我更新状态
我假设在我更新 Category 的状态后,调用应该得到更新,这不会发生。
状态得到更新(我在控制台中打印了它),但组件在收到它后没有发出新的调用。
完整代码在这里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);
解决方案
你不了解 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 后更新。
推荐阅读
- java - PageParameters 导致多次调用 Page 的 onConfigure
- java - 使用带有触发器的 JDBC 从 SQLServer 获取自动生成的密钥
- php - PHP / tmp 文件在请求中间消失 - 有时
- asp.net-identity - 有没有比通过 userManager.CreateAsync() 更快地批量创建身份用户(1M 行)的方法?
- exception - vue axios Uncaught (in promise) 取消
- c# - 带有 2 个参数的 ASP.NET 2.0 Web API 问题
- reactjs - Detox:条件测试用例编写
- c# - 将 NLog.Extended 从 2.0 升级到 4.6 后抛出“无法加载类型 NLog.Web.NLogHttpModule”
- python - 在python中交换十六进制字节数组中的字节对
- c++ - 如何在 C++ 中将 JWK 公钥转换为 PEM 格式