【问题标题】:Alert not displaying when receiving json response收到 json 响应时不显示警报
【发布时间】:2020-12-30 17:49:24
【问题描述】:

我故意发送错误请求以尝试触发警报。我尝试了很多方法来发出警报,但这似乎是最简洁的。但是,我尝试过的方法都没有奏效。 有人可以向我解释一下(因为我是新手)如何让这个警报显示响应?

这是我的代码:

        const { name, username, email, password, device_name } = this.state;
        console.log(this.state)

        fetch('myURL', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: this.state.name,
            username: this.state.username,
            email: this.state.email,
            password: this.state.password,
            device_name: this.state.device_name
          })
        }).then((response) => response.json())
        .then((jsonResponse) => console.log(jsonResponse)).catch(error => {Alert.alert(error.status, jsonResponse[0])});
    };

这是我在控制台日志中得到的响应数据:

Object {
  "response": Object {
    "email": Array [
      "The email field is required.",
    ],
    "name": Array [
      "The name field is required.",
    ],
    "password": Array [
      "The password field is required.",
    ],
  },
  "status": "error",
}

这是整个班级的代码:

import  React, {Component} from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {View, Text, StyleSheet, TextInput, Button, Alert} from 'react-native';
import * as SecureStore from 'expo-secure-store';

export default class Registration extends Component {
    constructor(props) {
      super(props);
      
      this.state = {
        name: '',
        username: '',
        email: '',
        password: '',
        device_name: 'testDeviceID'
      };
    }

    submitRegistration = async () => {
        const { name, username, email, password, device_name } = this.state;
        console.log(this.state)

        fetch('myURL', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: this.state.name,
            username: this.state.username,
            email: this.state.email,
            password: this.state.password,
            device_name: this.state.device_name
          })
        }).then((response) => response.json())
        .then((jsonResponse) => console.log(jsonResponse)).catch(error => {Alert.alert(error.status, jsonResponse[0])});
    };

    render() {
        return (
            <View style={style.container}>
                <Text style={style.title} >Registration</Text>
                <TextInput 
                    style={style.input}
                    value={this.state.name}
                    placeholder="your name"
                    onChangeText={(name) => this.setState({ name })}
                />
                <TextInput 
                    style={style.input}
                    value={this.state.username}
                    placeholder="username"
                    onChangeText={(username) => this.setState({ username })}
                />
                <TextInput 
                    style={style.input} 
                    value={this.state.email}
                    placeholder="email"
                    onChangeText={(email) => this.setState({ email })}
                />
                <TextInput 
                    style={style.input} 
                    value={this.state.password}
                    placeholder="password"
                    autoCapitalize="none"
                    autoCorrect={false}
                    onChangeText={(password) => this.setState({ password })}
                />
                <Button title='Register' onPress={this.submitRegistration.bind(this)}/>
            </View>
        )
    };
};

const style = StyleSheet.create({
    container: {
        flex: 1,
        padding: 24,
        backgroundColor: "#eaeaea",
        marginTop: 24
    },
    title: {
        marginTop: 16,
        paddingVertical: 8,
        borderWidth: 4,
        borderColor: "#20232a",
        borderRadius: 6,
        backgroundColor: "#9bc2cf",
        color: "#20232e",
        textAlign: "center",
        fontSize: 30,
        fontWeight: "bold"
      },
      input: {
        marginTop: 16,
        paddingVertical: 8,
        borderWidth: 4,
        borderColor: "#20232a",
        borderRadius: 6,
        backgroundColor: "#61dafb",
        color: "#20232a",
        textAlign: "center",
        fontSize: 30,
        fontWeight: "bold"
      }
});

【问题讨论】:

  • 获取数据时出错和成功获取其中一个字段中包含“错误”的数据是有区别的,后者不会使您的代码在catch中执行,您需要解析响应并检查状态

标签: reactjs react-native mobile


【解决方案1】:

看来您的问题已成定局。由于承诺可以很好地解决您正在记录的 json 数据,因此永远不会调用 catch 函数。

所以你的选择是:

  1. 当您收到来自后端的错误响应时,抛出带有 json 的 Error
.then((response) => response.json())
.then((jsonResponse) => { 
    if (response.status === "error") {
        let err = new Error(response.status);
        err.response = response;
    }
})
.catch(error => {Alert.alert(error.message, error.response)});
  1. 使用 then 而不是 catch 来触发警报而不考虑结果。
.then((response) => response.json())
.then(response => {Alert.alert(response.status, response)});

但您肯定需要阅读有关承诺的信息,以选择应用哪种解决方案。

【讨论】:

  • 你是对的!我没有使用您的确切解决方案,但是您将我引向了正确的解决方案。我没有意识到我从来没有抓住机会。所以谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
相关资源
最近更新 更多