【问题标题】:React-Native: access a function defined inside useEffect() - call it from outside useEffectReact-Native:访问 useEffect() 内部定义的函数 - 从 useEffect 外部调用它
【发布时间】:2021-12-07 17:03:40
【问题描述】:

有什么方法可以调用在 useEffect 中定义的函数(作为按钮的回调)?

组件的骨架如下:

useEffect(() => {
  const longFunction = async () => {
    ...
    const innerFunctionOne = async () => {
       ...
    }
    const innerFunctionTwo = async () => {
       ...
       innerFunctionOne()
    }

    ... some code
    ... some code
    innerFunctionTwo()
  }

  ...some code
  longFunction();
  
  return someCleanup;

},[])

...
...
<Button onPress={() => innerFunctionTwo()}

除了在useEffect之外取出函数定义,有没有办法从Button中访问呢? 谢谢

【问题讨论】:

    标签: reactjs react-native use-effect


    【解决方案1】:

    不知道实现的细节就很难说。因此,在不知道您的详细信息的情况下,我会将 longFunction 放在 useEffect 之外,将 innerFunctionTwo 放在 longFunction 之外。例如:

    function App() {
      const innerFnTwo = function() {
        console.log('innerFnTwo');
      };
    
      const longFn = function() {
        console.log('longFn');
        innerFnTwo();
      };
    
      React.useEffect(() => {
        longFn();
      }, []);
    
      return (
        <div>
          <button onClick={() => innerFnTwo()}>Click me</button>
        </div>
      );
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <div id="root"></div>

    【讨论】:

    • 谢谢 - 最后我把它移到了一个自定义的钩子上。
    • @Wasteland 对,如果您要通过应用程序在许多组件中使用该逻辑,将其放入自定义挂钩中是一个不错的决定。
    猜你喜欢
    • 2020-08-15
    • 2020-08-19
    • 2021-02-14
    • 2021-12-28
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多