如何在Context Provider React Native中导航内部函数

时间:2019-12-15 01:29:12

标签: reactjs react-native

我尝试使用Context Api并处理函数内部的导航。 我有:

SignupContext.js:

export const SignupProvider = ({ children }) => {

    const signup = async (username, email) => {
         const response = await api.post('/signup', {name, email});
         // How here do navigation.navigate('Main') ?
    }
}

SignupScreen.js:

<Button 
    title="Sign Up" 
    onSubmit={()=>signup(name, email)} 
/>

我如何使用类组件:

async signup() {
    const {navigate} = this.props.navigation; // <- Here set navigation prop
    // ... fetch data ... 
    navigate('Main') // <- Works good
}

在功能组件中,通常如下所示:

const func = ({ navigation }) => {
    navigation.navigate('Main')
}

如何使用 SignupContext.js 中的Context Provider?

1 个答案:

答案 0 :(得分:0)

有效的解决方案:

  1. 创建文件navRef.js
import { NavigationActions } from 'react-navigation';

let navigator;

export const setNavigator = (nav) => {
   navigator = nav;
};

export const navigate = (routeName, params) => {
   navigator.dispatch(
       NavigationActions.navigate({
           routeName,
           params
       })
   );
};
  1. 导入文件并添加导航
import { navigate } from '../navRef'; // <- import file

export const SignupProvider = ({ children }) => {

    const signup = async (username, email) => {
         const response = await api.post('/signup', {name, email});
         navigate('Main') // <- navigation to Main screen
    }
}