首页 > 解决方案 > React-Native:访问 useEffect() 内部定义的函数 - 从 useEffect 外部调用它

问题描述

有什么方法可以调用在 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中访问它?谢谢

标签: reactjsreact-nativeuse-effect

解决方案


不知道实现的细节是很难说的。因此,在不知道您的详细信息的情况下,我会将 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>


推荐阅读