首页 > 解决方案 > 如何从孩子调用父母的功能而不更新父母状态?

问题描述

在 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但不更新父状态。

标签: javascriptreactjsreact-hooksjsx

解决方案


万一你被这个困住了:

请使用以下方法通过:

//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....

推荐阅读