node.js - 从父组件触发一个函数 - 它将在子组件上运行 componentDidMount
问题描述
所以我得到了这个 React 项目 - 有一个管理页面,我可以添加新的假期(使用 Reactstrap Modal)。假期被添加到数据库中,并显示在名为 AdminVacations 的子组件中。假期的数组被加载到孩子的组件中。这是添加假期的代码(在管理组件中)
async Add (){
let NewVac = {
name:this.state.name,
price:this.state.price,
start:this.state.start,
end:this.state.end,
image:this.state.file,
description:this.state.description
}
let r = await fetch(`${apiUrl}/addvacation`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(NewVac)
});
let jsonData= await r.json();
if (r.status === 200){
this.toggle();
}
}
我还有编辑和删除按钮——在孩子的子组件中找到。问题是我需要在屏幕上显示更改(实时)。我设法使用编辑和删除按钮来做到这一点(因为它们位于同一个组件中)但添加按钮不存在。我怎样才能让假期状态从他的父亲组件再次重新加载到孩子的组件中?
import React, { Component } from 'react';
import apiUrl from './apiUrl';
import AdminVacation from './AdminVacation';
import AdminNavbar from './AdminNavbar'
class AdminVacations extends Component {
state={
Vacations:[],
userid:''
}
render() {
return (
<div className="container">
<div class="row">
{this.state.Vacations.map(data=> <AdminVacation key={data.id} data={data} RefreshFunc={this.RefreshFunc.bind(this)} />)}
</div>
</div>
)
}
async componentDidMount(){
let response = await fetch(`${apiUrl}/allvacations`);
let data = await response.json();
this.setState({ Vacations:data })
}
RefreshFunc(){
console.log("something Happened")
this.componentDidMount()
}
}
export default AdminVacations;
(基本上我想在每次添加假期时再次在子组件(来自管理员)中运行 componentDidMount - 而不仅仅是在我编辑或删除它时。编辑和删除位于 AdminVacation 组件中。
解决方案
您可以使用子组件中的componentDidUpdate生命周期方法来检查对props
. 简而言之,它是这样工作的。下面的代码检查当前的 props 和以前的 propslocation
是否不同,如果是,则执行if
块内的操作。
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0); // reset scroll on route change
}
}
推荐阅读
- jquery - 无法将 Json 数据加载到下拉列表
- nginx - 在谷歌入口控制器中建立 https 后 websocket 连接失败
- javascript - 导航悬停效果wordpress
- cmake - 如何根据生成器表达式 CONFIG 而不是 CMAKE_BUILD_TYPE 添加_子目录?
- reactjs - react-dates,当用户点击结束日期对应的输入字段时,应该显示结束日期对应的月份
- mongodb - 在不聚合的查找查询中获取 Mongo _id 作为字符串而不是 ObjectId
- java - 404 未找到 Tomcat 的 Spring Boot 战争
- c# - MVC 获取异常指定的强制转换无效
- mysql - SQL将doublon ID行合并为具有更多列的唯一行
- c# - 将数据(复杂数据/原始数据)发送到服务并获取响应(复杂数据/原始数据)的最佳方式(WCF 或 WEB API)