首页 > 解决方案 > React Native 上下文函数不是函数

问题描述

我正在尝试导入在“上下文”文件中定义的函数,以便可以轻松访问整个应用程序中的用户数据。

然而,当导入它并在我的“useEffect”中调用它时,它声称它不是一个函数——当它显然是时。

作为参考,这是我从中调用上下文函数的组件:

import { Context } from '../context/authContext';

const LoadingScreen = ({ navigation }) => {

  const { checkSignedIn } = useContext(Context)

  useEffect(() => {
    checkSignedIn()
  }, [])

  return (
    <View style={styles.mainView}>
      <ActivityIndicator style={styles.indicator} />
    </View>
  )
}

这是上下文文件本身(完整):

import createDataContext from './createDataContext';
import { navigate } from '../navigationRef';

import { Magic } from '@magic-sdk/react-native';
const m = new Magic('API key');

const authReducer = (state, reducer) => {
  switch (action.type) {
    case 'checkComplete':
      return { ...state, userDetails: action.payload };
    default:
      return state;
  }
};

const checkSignedIn = dispatch => {
  return async () => {
    // Set variable which calls Magic to check if signed in
    const checkMagic = await m.user.isLoggedIn();
    // If user signed in, redirect to dashboard and save details in state
    if (checkMagic === true) {
      const { issuer, email } = await m.user.getMetaData();
      dispatch({
        type: 'checkComplete',
        payload: [issuer, email]
      });
      navigate('authorisedFlow');
    // If user not signed in, redirect to welcome page and set state as null
    }
    else {
      navigate('loginFlow');
      }
    };
  };

export const { Context, Provider } = createDataContext( authReducer, { checkSignedIn }, { userDetails: null } );

这是名为“createDataContext”的“助手”函数,它遍历调度并定义它,而无需重复创建上下文代码:

import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key].dispatch;
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {children}
      </Context.Provider>
    )
  };

  return { Context, Provider }
};

我认为不需要在此处显示导航助手,但如果需要,我很乐意加入。似乎更多的是函数本身的问题!

如果有人能指出我在这里做错了什么,将不胜感激!

如果有任何不清楚的地方,请告诉我。

标签: reactjsreact-native

解决方案


推荐阅读