【问题标题】:problem with hook for react-native async functionreact-native 异步函数的钩子问题
【发布时间】:2019-07-07 16:20:59
【问题描述】:
我尝试加载字体系列,我使用了带有异步功能的钩子,但出现了一些错误:
function Button(props: TouchableOpacityProps & ButtonProps) {
useEffect(() => {
async function loadFont() {
await Font.loadAsync({
gotham_medium: require("../../assets/GothamMedium_1.ttf")
});
}
loadFont()
}, []);
return (
<TouchableOpacity {...props} style={styles.button}>
<Text style={styles.title}>{props.title}</Text>
</TouchableOpacity>
);
};
我从 expo 中导入了 Font,从 react 中导入了 useEffect,但是我遇到了这个错误。
error on the device
【问题讨论】:
标签:
javascript
reactjs
react-native
react-hooks
【解决方案1】:
这是我的应用程序中的内容,以防它对某人有所帮助。
useEffect(() => {
const loadFonts = async () => {
await Font.loadAsync({
'pokeh': require('../../assets/fonts/pokeh.ttf'),
});
setFontReady(true);
};
loadFonts();
}, []);
在使用 npm 安装 expo-font 后,这两个在顶部
import * as Font from 'expo-font';
import { AppLoading } from 'expo';
在这个树形结构下:
【解决方案2】:
您的错误可能是由错误的 React 版本产生的。您确定您至少使用 Expo SDK 33 吗?
如果这不是问题,我相信如果您在流程的早期加载所有资产可能会更容易。 Expo 提供了一个 AppLoading 组件,该组件采用 startAsync 属性,可以很容易地用于解决所有异步承诺。
所以你的App.js 可能看起来像:
import { AppLoading } from 'expo';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { StyleSheet, View, Text } from 'react-native';
export default function App(props) {
const [isLoadingComplete, setLoadingComplete] = useState(false);
if (!isLoadingComplete && !props.skipLoadingScreen) {
return (
<AppLoading
startAsync={loadResourcesAsync}
onError={handleLoadingError}
onFinish={() => handleFinishLoading(setLoadingComplete)}
/>
);
} else {
return (
<View style={styles.container}>
<Text style={styles.title}>Welcome to your Expo app</Text>
</View>
);
}
}
async function loadResourcesAsync() {
await Promise.all([
Font.loadAsync({
'gotham-medium': require('./assets/GothamMedium_1.ttf')
}),
]);
}
function handleLoadingError(error) {
console.warn(error);
}
function handleFinishLoading(setLoadingComplete) {
setLoadingComplete(true);
}
const styles = StyleSheet.create({
container: {
marginTop: 60,
flex: 1,
backgroundColor: '#fff',
},
title: {
fontFamily: 'gotham-medium',
fontSize: 36
}
});
然后您就可以在应用程序的任何位置访问fontFamily: 'gotham-medium'。您还可以在Promise.all() 调用中解决多个承诺(加载其他资产等)。
如果有帮助,请告诉我。干杯!