首页 > 解决方案 > 从父组件触发一个函数 - 它将在子组件上运行 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 组件中。

标签: node.jsreactjs

解决方案


您可以使用子组件中的componentDidUpdate生命周期方法来检查对props. 简而言之,它是这样工作的。下面的代码检查当前的 props 和以前的 propslocation是否不同,如果是,则执行if块内的操作。

componentDidUpdate(prevProps) {
  if (this.props.location !== prevProps.location) {
    window.scrollTo(0, 0); // reset scroll on route change
  }
}

推荐阅读