无法离开组件

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

标签: react-native formik

尽管尝试了this.props.navigation.navigate和NavigationService,我似乎也无法离开组件

为了进行测试,我创建了一个简单的按钮来导航,它可以工作,但是当我在formik和react-native中使用它时,它并没有导航

有人遇到过这种情况吗?您如何解决?下面是我的代码

谢谢

import React, { Component } from "react";
import {
  View,
  StyleSheet,
  AsyncStorage,
  Text,
  TouchableHighlight
} from "react-native";
import { Button } from "react-native-elements";
import { Formik } from "formik";
import * as Yup from "yup";
import { Mutation } from "react-apollo";

import Input from "../components/Input";
import NavigationService from "../../navigation/NavigationService";
import { SIGNIN } from "../../graphql/queries";

const FormValidationSchema = Yup.object().shape({
  email: Yup.string()
    .email("Not valid email")
    .required("Email is required"),
  password: Yup.string()
    .min(3)
    .required("Password is required")
});

class EmailSigninScreen extends Component {
  _handleSubmit = async (values, bag, signin) => {
    console.log(values, bag, signin);
    try {
      const data = await signin({
        variables: {
          email: values.email,
          password: values.password
        }
      });
      await AsyncStorage.setItem("token", data.signin.token);
      this.props.navigation.navigate("Main");
      // NavigationService.navigate("Main");
    } catch (error) {
      bag.setSubmitting(false);
      bag.setErrors(error);
    }
  };

  render() {
    const { container, buttonStyle } = styles;

    return (
      <View style={container}>
        <Mutation mutation={SIGNIN}>
          {(signin, { error }) => {
            console.log(error);
            return (
              <Formik
                initialValues={{ email: "", password: "" }}
                onSubmit={(values, bag) =>
                  this._handleSubmit(values, bag, signin)
                }
                validationSchema={FormValidationSchema}
                render={({
                  values,
                  handleSubmit,
                  errors,
                  touched,
                  setFieldValue,
                  setFieldTouched,
                  isValid,
                  isSubmitting
                }) => (
                  <React.Fragment>
                    <Input
                      label="Email"
                      autoCapitalize="none"
                      autoComplete="none"
                      value={values.email}
                      onChange={setFieldValue}
                      onTouch={setFieldTouched}
                      name="email"
                      error={touched.email && errors.email}
                    />
                    <Input
                      label="Password"
                      autoComplete={false}
                      autoCapitalize="none"
                      secureTextEntry
                      name="password"
                      value={values.password}
                      onChange={setFieldValue}
                      onTouch={setFieldTouched}
                      error={touched.password && errors.password}
                    />
                    <Button
                      backgroundColor="purple"
                      buttonStyle={buttonStyle}
                      title="Submit"
                      onPress={handleSubmit}
                      disabled={!isValid || isSubmitting}
                      loading={isSubmitting}
                    />
                    <TouchableHighlight
                      onPress={() => this.props.navigation.navigate("Main")}
                    >
                      <Text>Jump</Text>
                    </TouchableHighlight>
                  </React.Fragment>
                )}
              />
            );
          }}
        </Mutation>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center"
    // justifyContent: "center"
  },
  buttonStyle: {
    marginTop: 20,
    width: "100%"
  }
});

export default EmailSigninScreen;

2 个答案:

答案 0 :(得分:0)

尝试像这样与Navigation一起使用:

import { withNavigation } from 'react-navigation';

export default withNavigation(EmailSigninScreen);

其他所有东西都可以保持不变

答案 1 :(得分:0)

问题出在我的异步-等待语法分解

将我的handleSubmit函数分解为以下格式可以工作...

我仍在尝试查看是否可以将下面的代码转换为纯粹使用async和await而不是将async和await&然后混合并捕获的代码。如果有人有解决方案,请在这里提供建议。 Tq

  //TODO refactor to async and await syntax
  _handleSubmit = (values, bag, signin) => {
    signin({
      variables: {
        email: values.email,
        password: values.password
      }
    })
      .then(async ({ data }) => {
        if (data && data.signin.token) {
          await AsyncStorage.setItem("token", data.signin.token);
          this.props.navigation.navigate("Main");
        }
      })
      .catch(err => {
        bag.setSubmitting(false);
        bag.setErrors(err);
      });
  };