首页 > 解决方案 > 如何在反应js中从父组件的孙子调用另一个子组件的API

问题描述

我需要从一个孙子组件调用一个子组件中的 API,该子组件是主(父)组件的另一个子组件的子组件。这是我的组件的结构。

function MainComponent(){
    return(
        <div>
            <Child1Component />
            <Child2Component />
        </div>
    )
}

function Child1Component(){
    return(
        <div>
            <ModalComponent />
            
        </div>
    )
}

function ModalComponent(){

    const upadate = () => {
        //call API in Child2Component
    }

    return(
        <div>         
        </div>
    )
}

function Child2Component(){

    const fetch = () => {
        axios.get(ULR + '/api/mymethod').then(respose =>{

        })
    }

    return(
        <div>           
        </div>
    )
}

如果有更新<ModalComponent/>是 的子级<Child1Component/>,则应该在 中执行 API 调用,<Child2Component/>以便 Child2Component 可以更新,我的意思是它的状态应该在 API 调用之后更新。

请任何人都可以帮助我。

标签: reactjs

解决方案


你有三个选择:

  1. 在父级中使用共享上下文,然后将状态和设置状态函数分别传递给子级和孙级。(我认为在您的特定情况下的最佳解决方案)
  2. 使用 redux
  3. 创建父状态,然后将其直接传递给孩子(但是,由于您有子孙,它会很快变得混乱,所以我不建议您这样做)

这里的实现:

//Maincomponent.js

import React, {useState} from 'react';

export const SharedContext= React.createContext(undefined!)

function MainComponent(){

    const [myState, setMyState] = useState() //Initialize with anything you want

    return(
         <SharedContext.Provider value={{myState, setMyState}}>
            <div>
              <Child1Component />
              <Child2Component />
            </div>
         <SharedContext.Provider/>
    )
}

现在让我们更新状态:

import {useContext} from 'react';

import {SharedContext} from '../my/file/path';

function Child2Component(){

    const { myState, setMyState } = useContext(SharedContext);

    const fetch = () => {
        axios.get(ULR + '/api/mymethod').then(respose =>{
            //Update parent state through context
            setMyState(...) //insert your data
        })
    }

    return(
        <div>           
        </div>
    )
}

最后,让我们设置一个监听父状态变化的 useEffect Hook:

import {useEffect, useContext} from 'react';

import {SharedContext} from '../my/file/path';

function ModalComponent(){

    const { myState, setMyState } = useContext(SharedContext);

    useEffect(()=>{
       //Update here. This will be called every time you update parent state
    }
    ,[myState])

    return(
        <div>           
        </div>
    )
}

推荐阅读