我尝试使用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?
答案 0 :(得分:0)
有效的解决方案:
import { NavigationActions } from 'react-navigation';
let navigator;
export const setNavigator = (nav) => {
navigator = nav;
};
export const navigate = (routeName, params) => {
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
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
}
}