简体   繁体   English

在反应组件中多次使用 function 的最佳实践是什么?

[英]What is best practice for using a function multiple times in a react component?

I have component with some calculation functions and im looking for best practice for using my functions multiple times in other functions and conditions;我有一些计算功能的组件,我正在寻找在其他功能和条件下多次使用我的功能的最佳实践; without breaking rules or overusing useEffect and useState (or should i?).不违反规则或过度使用useEffectuseState (或者我应该?)。

export default function App() {
  const [data, setData] = React.useState({});
  const [render, setRender] = React.useState(0);
  const calculate1 = () => {
    if (data.object?.number > 100) return 256
    return 0
  }
  const calculate2 = () => {
    if (calculate1() > 0) return 0
    return 1
  }
  React.useEffect(() =>{
    axios.get('api').then((response) =>
    setData(response.data))
  },[])
  return (
    <div>
      {!!calculate1() && <h1>{calculate1()}</h1>}
      {!!calculate2() && <h2>{calculate1() + 1}</h2>}
      <button onClick={() => setRender(render+1)}>render</button>
    </div>
  );
}

1- Should i save calculated in a variable then use it anywhere? 1-我应该将计算结果保存在变量中然后在任何地方使用它吗? if yes, how to prevent calling calculations on each render with render button?如果是,如何防止使用渲染按钮在每个渲染上调用计算?

const result1 = calculate1()
const result2 = calculate2()

2- Should i use useMemo to keep calculations isolated? 2- 我应该使用useMemo来隔离计算吗? (calculations are not expensive) (计算不贵)

const result1 = React.useMemo(() => {
    if (data.object?.number > 100) return 256
    return 0
  }, [data])
const result2 = React.useMemo(() => {
    if (result1 > 0) return 0
    return 1
  },[result1])

3- Other solutions? 3- 其他解决方案?

Saving the result of the calculation like in 1 won't work because on each render the calculate1 and calculate2 runs again (you rightly identified that on a rerender it runs again).像在 1 中那样保存计算结果将不起作用,因为在每次渲染时, calculate1calculate2都会再次运行(您正确地确定在重新渲染时它会再次运行)。

Your example in 2 is correct if you want to memoise the values.如果您想记住这些值,那么您在 2 中的示例是正确的。 Generally though for non-expensive calculations you should skip useMemo .通常,尽管对于非昂贵的计算,您应该跳过useMemo There's overhead from using useMemo and it does make your code slightly more complex to read.使用useMemo会产生开销,并且确实会使您的代码阅读起来稍微复杂一些。 You should only consider useMemo if the calculation is computationally heavy (you should decide for yourself).如果计算量很大(您应该自己决定),您应该只考虑useMemo

But for your example I would just suggest:但对于你的例子,我只是建议:

const calculate1Value = data.object?.number > 100 ? 256 : 0
const calculate2Value = calculate1Value > 0 ? 0 : 1
// ...

I'm assuming calculate() was supposed to be calculate1() – in that case, I'd just do我假设calculate()应该是calculate1() - 在这种情况下,我会做

export default function App() {
  const [data, setData] = React.useState({});
  const [render, setRender] = React.useState(0);
  React.useEffect(() => {
    axios.get('api').then(({data}) => setData(data));
  }, []);
  const result1 = (data.object?.number > 100 ? 256 : 0);
  const result2 = (result1 > 0 ? 0 : 1);
  return (
    <div>
      {!!result1 && <h1>{result1}</h1>}
      {!!result2 && <h2>{result1 + 1}</h2>}
      <button onClick={() => setRender(render + 1)}>render</button>
    </div>
  );
}

and in case the actual computation was heavier than that and worth caching,并且如果实际计算比这更重并且值得缓存,

export default function App() {
  const [data, setData] = React.useState({});
  const [render, setRender] = React.useState(0);
  React.useEffect(() => {
    axios.get('api').then(({data}) => setData(data));
  }, []);
  const [result1, result2] = React.useMemo(() => {
    const result1 = (data.object?.number > 100 ? 256 : 0);
    const result2 = (result1 > 0 ? 0 : 1);
    return [result1, result2];
  }, [data]);
  return (
    <div>
      {!!result1 && <h1>{result1}</h1>}
      {!!result2 && <h2>{result1 + 1}</h2>}
      <button onClick={() => setRender(render + 1)}>render</button>
    </div>
  );
}

Finally, if the same computation is required in multiple components, I would wrap it in a hook:最后,如果多个组件需要相同的计算,我会将其包装在一个钩子中:

function useResults(data) {
  const [result1, result2] = React.useMemo(() => {
    const result1 = (data.object?.number > 100 ? 256 : 0);
    const result2 = (result1 > 0 ? 0 : 1);
    return [result1, result2];
  }, [data]);
  return {result1, result2};
}

export default function App() {
  const [data, setData] = React.useState({});
  const [render, setRender] = React.useState(0);
  React.useEffect(() => {
    axios.get('api').then(({data}) => setData(data));
  }, []);
  const {result1, result2} = useResults(data);
  return (
    <div>
      {!!result1 && <h1>{result1}</h1>}
      {!!result2 && <h2>{result1 + 1}</h2>}
      <button onClick={() => setRender(render + 1)}>render</button>
    </div>
  );
}

and if it was always paired with the same data fetch,如果它总是与相同的数据获取配对,

function useDataAndResults() {
  const [data, setData] = React.useState({});
  React.useEffect(() => {
    axios.get('api').then(({data}) => setData(data));
  }, []);
  const [result1, result2] = React.useMemo(() => {
    const result1 = (data.object?.number > 100 ? 256 : 0);
    const result2 = (result1 > 0 ? 0 : 1);
    return [result1, result2];
  }, [data]);
  return {data, result1, result2};
}

export default function App() {
  const [render, setRender] = React.useState(0);
  const {data, result1, result2} = useDataAndResults();
  return (
    <div>
      {!!result1 && <h1>{result1}</h1>}
      {!!result2 && <h2>{result1 + 1}</h2>}
      <button onClick={() => setRender(render + 1)}>render</button>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 React 组件中多次使用 this.setState 会发生什么? - What happens when using this.setState multiple times in React component? react.js 在组件中使用常量值的最佳实践是什么 - What is the best practice in react.js to use a constants value in a component 快速试用 React 组件的最佳实践是什么? - What's best practice to quickly try out a React component? 是否有使用反应路由器隐藏组件的最佳实践方法? - Is there a best practice way to hide component using react router? React Native组件样式的最佳实践 - Best practice for React Native component styling 在 React 组件中多次重复作为道具传递的函数 - Repeating a Function Passed as a Props in React Component Multiple Times Function 在 React 功能组件中被多次调用 - Function being called multiple times in React functional component 使用$ resource并在多个控制器之间共享结果的最佳实践是什么? - What is the best practice for using $resource and sharing the results across multiple controllers? 在这种情况下,使用IF或SWITCH或“动态功能名称”的最佳实践是什么 - Javascript What is best practice using IF or SWITCH or “dynamic function name” in this case 阻止 function 在 Js 中多次运行的最佳方法是什么 - What is the best way to stop function from running multiple times in Js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM