[英]How to call function of a parent from child and do not update the parent state?
在 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....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.