reactjs - 对路由器更改做出反应重新安装
问题描述
我在 reactjs 中有一个简单的 post 组件,该组件根据 id 从 db 打印 post 数据,id 是从 url 中挑选的(我为此使用 react 路由器),并且数据是由 ajax 调用挑选的。问题是,当我更改页面组件不更新内容时,更新仅在我刷新页面时发生。
class Post extends Component {
constructor(props) {
super();
this.state = {
thePost: '',
};
}
componentDidMount(){
axios.get(endpoint.posts+'/getpost/'+this.props.match.params.id, cfg)
.then(res => {
this.setState({
thePost: res.data.thePost || ''
});
})
}
render () {
return (
<div>POST { this.props.match.params.id } - { JSON.stringify(this.state.thePost, null, 0) }</div>
)
}
}
export default Post;
现在的问题是每次页面更改都不会调用 componentDidMount,我如何强制重新安装?或者我需要在组件的其他生命周期部分中移动 ajax 调用?
我发现了一些类似的问题,但太老了,尊重实际的 reactjs 和 react 路由器版本。
解决方案
像这样做。componentDidUpdate
如果当前 url 与之前的不匹配,请检查 url 更改再次发出 API 请求。
componentDidMount(){
this.getPosts()
}
getPosts = () => {
axios.get(endpoint.posts+'/getpost/'+this.props.match.params.id, cfg)
.then(res => {
this.setState({
thePost: res.data.thePost || ''
});
})
}
componentDidUpdate(prevProps) {
if (this.props.match.params.id !== prevProps.match.params.id) {
this.getPosts()
}
}
推荐阅读
- ios - 如何使用 Firebase 云功能通知有效负载重置应用图标的徽章编号?
- mysql - MYSQL 根据循环日期范围运行数据
- jasper-reports - jasper print not working 错误说 xml 解析错误
- java - 如何获取 apolloclient 的 Android GraphQL 查询响应的内部字段?
- django - Django 找不到存在于 postgreSQL 数据库中的表
- asp.net-core - 您可以在两种查询类型之间创建一对一的关系吗?
- python - 数值积分 Python 与 Matlab
- python - Keras:model.fit() 和 model.fit_generator() 返回历史对象。如何获得 Keras 模型?
- docker - 如何找到主机中的 docker 容器目录在哪里?
- pandas - 遍历数据框列以查看单个单元格值是否在文件路径列表中