reactjs - 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中访问它?谢谢
解决方案
不知道实现的细节是很难说的。因此,在不知道您的详细信息的情况下,我会将 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>
推荐阅读
- c# - 将 IQueryable 映射到 .NET 中 OData 的域模型
- azure-devops - VSTS 构建“魔法”变量
- jquery - 加载 jquery 后在正文中附加内容
- scala - 找不到 Spark-submit -class 命令?
- android - Android:以编程方式在菜单中添加分隔符
- apache-spark - spark shuffle write 超级慢
- r - 如何创建一个循环以迭代地从回归方程中删除系数
- uuid - 需要一个不会随软件更新而改变的唯一标识符
- google-sheets - 如何根据谷歌表的第一列交替颜色
- r - 将多个时间序列列强制为大型数据框中的因素