【问题标题】:How to call function of a parent from child and do not update the parent state?如何从孩子调用父母的功能而不更新父母状态?
【发布时间】:2021-01-21 16:06:15
【问题描述】:

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

【问题讨论】:

  • 不要让 setState 命令成为函数的一部分,而是将函数限制为请求本身(即让它只返回 ajax.get 调用)。然后在子组件中使用props.fetchData().then(response =&gt; ...)。或者,将正确的setState 方法作为参数传递给fetchData
  • 我知道这是一个非常基本的解决方案,但如果项目变成大文件,还有其他方法可以实现吗? @ChrisG
  • 嗯,这也是一个非常基本的问题 :) 我不明白为什么项目规模很重要;我的解决方案创建了一个通用函数来获取数据,这使其非常适合大型项目。不确定您在这里想象的其他解决方案是什么?
  • 好吧,我明白我可能很难接受。好的,我会考虑您建议的更改并尝试这种方法。

标签: javascript reactjs react-hooks jsx


【解决方案1】:

如果你遇到这个问题:

请使用以下方式打通:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多