React JS – 将多个函数传递给另一个函数

huangapple go评论59阅读模式
英文:

React JS - passing multiple functions to another function

问题

我正在尝试编写一段可以从多个 useEffect() 中调用的参数化代码,但似乎无法弄清楚语法,因此非常感谢任何输入/建议。

有人能建议我需要使用哪种语法来处理 initialActionsfinalActions,它们每个都应该是 useState 上的一个或多个“setter”。

const getDataItems = ({initialActions = [], finalActions = []}) => {
  setCommonPieceOfState(true);
  ...initialActions

  doFetch(someApi())
      .then(parseResponse)
      .then(handleError)
      .then(extractData)
      .catch(errorHandler)
      .finally(() => {
        ...finalActions
        setCommonPieceOfState(false);
      })
}

useEffect(() => {
  if (somePieceOfState) {
    getDataItems({
      initialActions: [specificInitialActionOne(), specificInitialActionTwo()],
      finalActions: [specificFinalActionOne()]
    });
  }
}, [somePieceOfState]);

useEffect(() => {
  if (someOtherPieceOfState) {
    getDataItems({
      initialActions: [specificInitialActionThree()],
      finalActions: [specificFinalActionTwo(), specificFinalActionThree(), specificFinalActionFour()]
    });
  }
}, [someOtherPieceOfState]);

以上伪代码粗糙,但希望足以传达这个想法。非常感谢任何想法/建议,如果以上内容不清楚,也欢迎提出更多信息的请求。我建议 initialActionsfinalActions 在上面的片段中是数组,但如果有更好的方法,那也可以不是数组。

提前感谢!

英文:

I'm trying to write a piece of parameterised code that can be called from multiple useEffect()s but cant seem to work the syntax out, so grateful for any input/suggestions.

Can anyone suggest the syntax I need to employ to deal with initialActions and finalActions, each of which are intended to be one-or-more 'setters' on useState.

  const getDataItems = ({initialActions = [], finalactions = []}) => {
    setCommonPieceOfState(true);
    ...initialActions

    doFetch(someApi())
        .then(parseResponse)
        .then(handleError)
        .then(extractData)
        .catch(errorHandler)
        .finally(() => {
        ...finalactions
          setCommonPieceOfState(false);
        })
  }

  useEffect(() => {
    if (somePieceOfState) {
      getDataItems({
        initialActions: [specificInitialActionOne(), specificInitialActionTwo()],
        finalActions: [specificFinalActionOne()]
      })    }
  }, [somePieceOfState]);

  useEffect(() => {
    if (someOtherPieceOfState) {
      getDataItems({
        initialActions: [specificInitialActionThree()],
        finalActions: [specificFinalActionTwo(), specificFinalActionThree(), specificFinalActionFour()]
      })    }
  }, [someOtherPieceOfState]);

The above pseudo code is coarse, but hopefully sufficient to convey the idea? Grateful for any thoughts/suggestions/requests for more info if the above isnt clear. I've suggested that initialActions and finalActions are arrays in the above snippet, but that needn't be the case if there's a better way

Thanks in advance,

答案1

得分: 0

尝试以下更改:

  • 从initialActions和finalActions数组元素中删除括号,因为您希望传递函数本身,而不是它们的结果。

  • 使用Promise.all在开始数据获取之前执行所有初始操作,并在完成获取后执行所有最终操作。

以下是代码:

const getDataItems = ({ initialActions = [], finalActions = [] }) => {
  setCommonPieceOfState(true);

  // 并发执行所有初始操作
  Promise.all(initialActions.map((action) => action()))
    .then(() => doFetch(someApi()))
    .then(parseResponse)
    .then(handleError)
    .then(extractData)
    .catch(errorHandler)
    .finally(() => {
      // 并发执行所有最终操作
      Promise.all(finalActions.map((action) => action()))
        .finally(() => {
          setCommonPieceOfState(false);
        });
    });
};

useEffect(() => {
  if (somePieceOfState) {
    getDataItems({
      initialActions: [specificInitialActionOne, specificInitialActionTwo],
      finalActions: [specificFinalActionOne],
    });
  }
}, [somePieceOfState]);

useEffect(() => {
  if (someOtherPieceOfState) {
    getDataItems({
      initialActions: [specificInitialActionThree],
      finalActions: [
        specificFinalActionTwo,
        specificFinalActionThree,
        specificFinalActionFour,
      ],
    });
  }
}, [someOtherPieceOfState]);
英文:

Try these changes:

  • Remove parentheses from the initialActions and finalActions array elements, as you want to pass the functions themselves, not their results.

  • Use Promise.all to execute all the initial actions before starting the data fetch and all the final actions after completing the fetch.

Here the code:

const getDataItems = ({ initialActions = [], finalActions = [] }) => {
  setCommonPieceOfState(true);

  // Execute all initial actions concurrently
  Promise.all(initialActions.map((action) => action()))
    .then(() => doFetch(someApi()))
    .then(parseResponse)
    .then(handleError)
    .then(extractData)
    .catch(errorHandler)
    .finally(() => {
      // Execute all final actions concurrently
      Promise.all(finalActions.map((action) => action()))
        .finally(() => {
          setCommonPieceOfState(false);
        });
    });
};

useEffect(() => {
  if (somePieceOfState) {
    getDataItems({
      initialActions: [specificInitialActionOne, specificInitialActionTwo],
      finalActions: [specificFinalActionOne],
    });
  }
}, [somePieceOfState]);

useEffect(() => {
  if (someOtherPieceOfState) {
    getDataItems({
      initialActions: [specificInitialActionThree],
      finalActions: [
        specificFinalActionTwo,
        specificFinalActionThree,
        specificFinalActionFour,
      ],
    });
  }
}, [someOtherPieceOfState]);

huangapple
  • 本文由 发表于 2023年7月23日 14:48:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76746949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定