I'm working on my React Native project and I'm getting the famous " Can't perform a React state update on an unmounted component
" sometimes when I'm using my custom text component. This is quite weird, because I'm following the same steps as the docs. Here's the component:
import React, { FunctionComponent } from "react";
import { Text, TextStyle } from "react-native";
import { AppLoading } from "expo";
import {
useFonts,
Montserrat_500Medium,
Montserrat_800ExtraBold,
} from "@expo-google-fonts/montserrat";
import { colors } from "./ConstantStyles";
type CustomTextProps = {
style?: TextStyle | TextStyle[];
variant?: string;
};
const PrimaryText: FunctionComponent<CustomTextProps> = ({
children,
style,
variant,
}) => {
let [fontsLoaded] = useFonts({
Montserrat_500Medium,
Montserrat_800ExtraBold,
});
const passedStyles = Array.isArray(style)
? Object.assign({}, ...style)
: style;
if (!fontsLoaded) {
return <AppLoading />;
} else {
return (
<Text
style={[
{
fontFamily:
variant === "bold"
? "Montserrat_800ExtraBold"
: "Montserrat_500Medium",
},
{ ...passedStyles },
]}
>
{children}
</Text>
);
}
};
export default PrimaryText;
What am I doing wrong?
You can try loading the fonts in async manner and keep a check in your useEffect
to setState only if its not unmounted, like given in this expo documentation using-fontloadasync-instead-of-the-usefonts-hook
Here is the expo snack example
Also, I would suggest to load fonts from local cache instead from direct web, which will increase the app size a little bit, but fonts will load much faster, just like given in the above example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.