javascript - 如何从孩子调用父母的功能而不更新父母状态?
问题描述
在 React 16.X 中,我的父组件中有函数:
const fetchData = ()=> {
return ajax
.get({},data)
.then((response) =>
{
setState(response);
// Here I update the state with setState()
})
.catch((error) =>
{
});
};
现在我把这个传给我的孩子props
:
<child fetchData={fetchData}/>
在我的孩子中,我选择:
const {fetchData} = props;
// from my parent
但是当我fetchData
从我的孩子那里打电话时,它会更新我父母的状态(因为setState
)。我想要的只是重用该fetchData
函数以从 API 获取数据,而不是更改父级的状态。
有没有可能的方法来实现这一目标?我想重用该功能fetchData
但不更新父状态。
解决方案
万一你被这个困住了:
请使用以下方法通过:
//define a function that only returns the request
const request = () =>{
return ajax
.get({},data);
};
//In anywhere else use it like this in main function
const fetchData = async ()=> {
const request = this.request();
return request
.then((response) =>
{
setState(response);
// Here I update the state with setState()
})
.catch((error) =>
{
});
};
//Or pass it in the props to use in the child component as
//In parent
<Abc requestFunc={this.request}/>
//and in Abc Component
const abc= (props)=>{
const requestCall = {props}
}
//call requestCall
requestCall().then....
推荐阅读
- java - 当我尝试建立与 MySQL 的连接时,我得到以下信息。java.math.BigInteger 不能转换为 java.lang.Long
- javascript - 在 Javascript 对象中搜索特定 ID 的位置?
- html - Bootstrap3 和导航栏,我怎样才能将这个 li 标签对齐到右边?
- caffe - 为什么 num_output 是卷积参数?
- angular - Angular 6 CLI 工作区。如何创建导出服务的库
- swift - 如何在导航栏下方提供图像视图填充?
- javascript - Angular 2 应用程序 - 获取 mp3 上传的持续时间
- elasticsearch - Elasticsearch 6.2 - 如何在无痛内联脚本中格式化 yyyymm 字符串中的日期(纪元)字段
- mule - GZip解压缩组件问题
- javascript - 如何禁用 Angular Material Stepper 中的步骤?