Android 如何在react native中成功发送操作后显示toast

Android 如何在react native中成功发送操作后显示toast,android,reactjs,react-native,Android,Reactjs,React Native,我正在研究一个认证系统。在这里,当用户输入错误的密码,我想显示土司,但问题是它的方式,我做它不工作 我正在我的应用程序中使用react redux进行状态管理 下面是我的登录流程的工作原理 在这里,当按下登录按钮时,它将调度getLogin操作,如果从服务器端收到错误,它将发送loginError,这是一个字符串。这就是为什么我在这里检查它登录错误来自redux商店,并且登录成功 Login.tsx authReducer.tsx 我不确定我做的是对还是错,请帮我解决这个问题。即使登录成功,此t

我正在研究一个认证系统。在这里,当用户输入错误的密码,我想显示土司,但问题是它的方式,我做它不工作

我正在我的应用程序中使用react redux进行状态管理

下面是我的登录流程的工作原理 在这里,当按下登录按钮时,它将调度
getLogin
操作,如果从服务器端收到错误,它将发送loginError,这是一个字符串。这就是为什么我在这里检查它<代码>登录错误来自redux商店,并且
登录成功

Login.tsx

authReducer.tsx


我不确定我做的是对还是错,请帮我解决这个问题。即使登录成功,此toast也会显示。

您应该在呈现之前设置该条件 类组件

import {useSelector, useDispatch} from 'react-redux'
const { width: wWidth, height: wHeight } = Dimensions.get("window");



const validationSchema = Yup.object().shape({
  password: Yup.string().required(),
  email: Yup.string().email().required(),
});

const Login = ({ navigation, getLogin, authentication }: LoginProps) => {
  const { toast } = useToast();
  const authentication = useSelector(state => state.auth);
  const { loginLoading, loginSuccess, loginError } = authentication;
  const dispatch = useDispatch();
  

  const {
    handleChange,
    handleBlur,
    handleSubmit,
    values,
    errors,
    touched,
    setFieldValue,
  } = useFormik({
    validationSchema,
    initialValues: {
      password: "",
      email: "",
      callback: false,
    },
    onSubmit: async (values) => {
      dispatch(userLogin(email, password, navigation)) // You call directly your action
    },
  });

  if (loginError !== "" && loginSuccess === "") {
    console.log("HelloFromIf");
    toast({
      message: "Wrong username or password!",
      bg: "background",
      color: "text",
      accentColor: "main",
      iconFamily: "Feather",
      iconName: "alert-triangle",
      iconColor: "error",
    });
  }
  return (
    <Box
      backgroundColor="primaryText"
      flex={1}
      justifyContent="center"
      alignItems="center"
    >
      <Box
        justifyContent="center"
        alignItems="center"
        height={wHeight / 2}
        width={wWidth}
        flex={1}
      >
        <Box style={{ marginTop: 100 }} height={wHeight / 3} width={wWidth / 2}>
          <Image
            style={{ height: "100%", width: "100%" }}
            source={require("../../../assets/login-logo.png")}
          />
        </Box>
      </Box>
      <Box
        borderTopLeftRadius="l"
        borderTopRightRadius="l"
        width={wWidth}
        backgroundColor="iconBackground"
        flex={1}
      >
        <Box marginHorizontal="l">
          <Box>
            <TextField
              onChangeText={handleChange("email")}
              placeholder="email"
              onBlur={handleBlur("email")}
              error={errors.email}
              touched={touched.email}
            />
          </Box>
          <Box>
            <TextField
              secureTextEntry={true}
              placeholder="Password"
              onChangeText={handleChange("password")}
              onBlur={handleBlur("password")}
              error={errors.password}
              touched={touched.password}
            />
          </Box>
          <LargeButton
            loading={loginLoading}
            onPress={handleSubmit}
            label={"LOGIN"}
          />
          <Box paddingVertical="m" alignItems="center">
            <TouchableWithoutFeedback>
              <Text variant="seeAll">Forgot Password ?</Text>
            </TouchableWithoutFeedback>
          </Box>

          <Box paddingVertical="m" alignItems="center">
            <TouchableWithoutFeedback
              onPress={() => navigation.navigate("SignUp")}
            >
              <Text variant="seeAll">Create new account!</Text>
            </TouchableWithoutFeedback>
          </Box>
        </Box>
      </Box>
    </Box>
  );
};


export default Login;
从'react redux'导入{useSelector,useDispatch}
const{width:wWidth,height:wHeight}=Dimensions.get(“窗口”);
const validationSchema=Yup.object().shape({
密码:Yup.string().required(),
电子邮件:Yup.string().email().required(),
});
常量登录=({navigation,getLogin,authentication}:LoginProps)=>{
const{toast}=useToost();
const authentication=useSelector(state=>state.auth);
const{loginLoading,loginsucess,loginError}=身份验证;
const dispatch=usedpatch();
常数{
handleChange,
车把,
手推,
价值观
错误,
感动的,
setFieldValue,
}=useFormik({
验证模式,
初始值:{
密码:“”,
电邮:“,
回调:false,
},
onSubmit:async(值)=>{
dispatch(userLogin(电子邮件、密码、导航))//您直接调用您的操作
},
});
如果(loginError!==”&&LoginAccess==”){
console.log(“HelloFromIf”);
吐司({
消息:“错误的用户名或密码!”,
背景:“背景”,
颜色:“文本”,
accentColor:“主”,
我的家人:“羽毛”,
iconName:“警报三角”,
iconColor:“错误”,
});
}
返回(
忘记密码了?
导航。导航(“注册”)}
>
创建新帐户!
);
};
导出默认登录;

您需要使用
useffect
在状态更新时执行副作用

您可以用以下代码替换当前代码:

useEffect(() => {
  if (loginError !== "" && loginSuccess === "") {
    console.log("HelloFromIf");
    toast({
      message: "Wrong username or password!",
      bg: "background",
      color: "text",
      accentColor: "main",
      iconFamily: "Feather",
      iconName: "alert-triangle",
      iconColor: "error",
    });
  }
}, [loginError, loginSuccess]);
每次loginError或LoginAccess更改时,该函数都将运行,并在满足条件时显示toast


顺便说一句,您可能应该看看这一点,以改进您的身份验证流程:

编辑您的问题并在提交的地方添加所有代码i使用完整登录更新了我的问题查看我的更新,了解有关挂钩的信息使用useDispatch和useSelector更好。useEffect可能容易出错
import {
  LOGIN_USER_LOADING,
  USER_SIGN_UP_ERROR,
  USER_SIGN_UP_LOADING,
} from "./../actions/constants/authConstant";
import {
  LOGIN_USER_SUCCESS,
  LOGIN_USER_ERROR,
  LOGOUT_USER,
} from "../actions/constants/authConstant";
import { USER_AUTHORIZED } from "../actions/constants/authConstant";
import { USER_SIGN_UP } from "../actions/constants/authConstant";

export type AuthState = {
  readonly isAuthenticated: boolean;
  readonly userData: {};
  readonly loginLoading: boolean;
  readonly loginSuccess: string;
  readonly loginError: string;

};

const initialState: AuthState = {
  isAuthenticated: false,
  userData: {},
  loginLoading: false,
  loginSuccess: "",
  loginError: "",

};

const authReducer = (state = initialState, action: any) => {
  switch (action.type) {
    
    case LOGIN_USER_LOADING:
      return {
        ...state,
        loginLoading: true,
        isAuthenticated: false,
        loginError: "",
        loginSuccess: "",
      };

    case LOGIN_USER_SUCCESS:
      return {
        ...state,
        isAuthenticated: true,
        loginLoading: false,
        userData: action.payload,
        loginError: "",
        loginSuccess: "User Logged In.",
      };
    case LOGIN_USER_ERROR:
      return {
        ...state,
        loginLoading: false,
        loginError: action.error,
        loginSuccess: "",
      };
    
    default:
      return {
        ...state,
      };
  }
};

export default authReducer;
import {useSelector, useDispatch} from 'react-redux'
const { width: wWidth, height: wHeight } = Dimensions.get("window");



const validationSchema = Yup.object().shape({
  password: Yup.string().required(),
  email: Yup.string().email().required(),
});

const Login = ({ navigation, getLogin, authentication }: LoginProps) => {
  const { toast } = useToast();
  const authentication = useSelector(state => state.auth);
  const { loginLoading, loginSuccess, loginError } = authentication;
  const dispatch = useDispatch();
  

  const {
    handleChange,
    handleBlur,
    handleSubmit,
    values,
    errors,
    touched,
    setFieldValue,
  } = useFormik({
    validationSchema,
    initialValues: {
      password: "",
      email: "",
      callback: false,
    },
    onSubmit: async (values) => {
      dispatch(userLogin(email, password, navigation)) // You call directly your action
    },
  });

  if (loginError !== "" && loginSuccess === "") {
    console.log("HelloFromIf");
    toast({
      message: "Wrong username or password!",
      bg: "background",
      color: "text",
      accentColor: "main",
      iconFamily: "Feather",
      iconName: "alert-triangle",
      iconColor: "error",
    });
  }
  return (
    <Box
      backgroundColor="primaryText"
      flex={1}
      justifyContent="center"
      alignItems="center"
    >
      <Box
        justifyContent="center"
        alignItems="center"
        height={wHeight / 2}
        width={wWidth}
        flex={1}
      >
        <Box style={{ marginTop: 100 }} height={wHeight / 3} width={wWidth / 2}>
          <Image
            style={{ height: "100%", width: "100%" }}
            source={require("../../../assets/login-logo.png")}
          />
        </Box>
      </Box>
      <Box
        borderTopLeftRadius="l"
        borderTopRightRadius="l"
        width={wWidth}
        backgroundColor="iconBackground"
        flex={1}
      >
        <Box marginHorizontal="l">
          <Box>
            <TextField
              onChangeText={handleChange("email")}
              placeholder="email"
              onBlur={handleBlur("email")}
              error={errors.email}
              touched={touched.email}
            />
          </Box>
          <Box>
            <TextField
              secureTextEntry={true}
              placeholder="Password"
              onChangeText={handleChange("password")}
              onBlur={handleBlur("password")}
              error={errors.password}
              touched={touched.password}
            />
          </Box>
          <LargeButton
            loading={loginLoading}
            onPress={handleSubmit}
            label={"LOGIN"}
          />
          <Box paddingVertical="m" alignItems="center">
            <TouchableWithoutFeedback>
              <Text variant="seeAll">Forgot Password ?</Text>
            </TouchableWithoutFeedback>
          </Box>

          <Box paddingVertical="m" alignItems="center">
            <TouchableWithoutFeedback
              onPress={() => navigation.navigate("SignUp")}
            >
              <Text variant="seeAll">Create new account!</Text>
            </TouchableWithoutFeedback>
          </Box>
        </Box>
      </Box>
    </Box>
  );
};


export default Login;
useEffect(() => {
  if (loginError !== "" && loginSuccess === "") {
    console.log("HelloFromIf");
    toast({
      message: "Wrong username or password!",
      bg: "background",
      color: "text",
      accentColor: "main",
      iconFamily: "Feather",
      iconName: "alert-triangle",
      iconColor: "error",
    });
  }
}, [loginError, loginSuccess]);