reactjs - 如何在反应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 调用之后更新。
请任何人都可以帮助我。
解决方案
你有三个选择:
- 在父级中使用共享上下文,然后将状态和设置状态函数分别传递给子级和孙级。(我认为在您的特定情况下的最佳解决方案)
- 使用 redux
- 创建父状态,然后将其直接传递给孩子(但是,由于您有子孙,它会很快变得混乱,所以我不建议您这样做)
这里的实现:
//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>
)
}
推荐阅读
- linux - docker 容器中的节点无法使用 node_modules 文件夹
- excel - 将 Excel 工作表从一个工作簿移动到另一个工作簿
- woocommerce - 在 WooCommerce 管理订单页面上显示折扣税详情
- java - 我将如何在不同的行(java)上创建平滑的垂直文本波浪?
- spring-kafka - EmbeddedKafka w/ContainerTestUtils.waitForAssignment 抛出:预期为 1,但得到 0 个分区
- python - 熊猫可以正确处理 datetime.datetime 子类吗?
- amazon-web-services - 使用 Terraform 动态创建多个 WAF 规则
- python - 使用键值修改 Json 文件
- python - Keras/ImageAI 对每张图片进行相同的分类
- python - 如果在 for 循环中找不到 re.findall 匹配项,如何打印?