如何解决ContextProvider中使用toast notification的showToast函数错误?
React Native中react-native-toast-notifications报错TypeError: showToast is not a function的解决方法
问题重现
认证上下文代码
import { useToast } from "react-native-toast-notifications"; export const AuthContext = createContext(); export const AuthContextProvider = ({ children }) => { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [token, setToken] = useState(AsyncStorageLib.getItem("Token")); const [user, setUser] = useState(!!token); const show = useToast(); const onLogin = (email, password) => { setIsLoading(true); loginRequest(email, password) .then((u) => { setUser(u); setToken(u.token); setIsLoading(false); }) .catch((e) => { setIsLoading(false); show("Login failed!", { type: "error" }); }); };
App.js代码
return ( <> <ThemeProvider theme={theme}> <ToastProvider> <AuthContextProvider> <Navigation /> </AuthContextProvider> </ToastProvider> </ThemeProvider> <ExpoStatusBar style="auto" /> </> );
报错信息
Uncaught (in promise) TypeError: showToast is not a function
解决方法
错误根源是useToast钩子返回的是包含showToast方法的对象,而非直接返回函数。你直接将useToast()赋值给show并调用,实际调用的是整个对象,而非内部的showToast方法。
修改步骤:
- 在
AuthContextProvider中,将const show = useToast();改为解构获取showToast方法:
const { showToast } = useToast();
- 然后在catch块中调用该方法:
showToast("Login failed!", { type: "error" });
如果想保留自定义变量名,也可以这样写:
const toast = useToast(); // 调用时 toast.showToast("Login failed!", { type: "error" });
额外优化提示:AsyncStorageLib.getItem("Token")是异步操作,直接作为useState初始值会得到Promise对象,建议用useEffect来初始化token:
useEffect(() => { const getToken = async () => { const storedToken = await AsyncStorageLib.getItem("Token"); setToken(storedToken); setUser(!!storedToken); }; getToken(); }, []);
内容的提问来源于stack exchange,提问作者mightycode Newton
相关产品推荐
相关产品推荐

