如何从子级调用父级函数并且不更新父级状态?

时间:2020-10-06 18:10:40

标签: javascript reactjs react-hooks jsx

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

1 个答案:

答案 0 :(得分:0)

如果您对此感到困惑:

请按照以下步骤操作:

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