【问题标题】:how to add error handling in react native redux component?如何在 react native redux 组件中添加错误处理?
【发布时间】:2020-11-05 02:24:31
【问题描述】:

我想为redux错误的组件添加句柄处理,如何在这个组件中添加,正常的警报工作但我想在组件中渲染错误以避免发生错误时应用程序崩溃??在这种情况下,我该如何实现呢??

import React, { useState } from "react";
import { connect } from "react-redux";
import * as actions from "../actions";
import { Text, View, TextInput, Alert, TouchableOpacity } from "react-native";
const Forgetpassword = (props) => {
  const { error, reset, success, isFetching } = props;
  const [data, setData] = React.useState({
    email: "",
  });
  const textInputChange = (val) => {
    setData({
      ...data,
      email: val,
    });
  };
  const handleOnSubmit = (event) => {
    reset(data);
    Alert.alert("Success", "Forgot password link successfully sent to mail");
  };
  return (
    <View style={styles.container}>
      <View style={styles.inputsContainer}>
        <View style={styles.input}>
          <TextInput
            style={styles.inputText}
            name="email"
            placeholder="Email"
            onChangeText={(val) => textInputChange(val)}
            textContentType="emailAddress"
          />
        </View>
        <View style={styles.inputBtn}>
          <TouchableOpacity onPress={handleOnSubmit}>
            <Text style={styles.btnText}>Reset</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
};
const mapStateToProps = (state) => {
  const { success, error, isFetching } = state.password;
  return {
    success,
    error,
    isFetching,
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    reset: (person) => {
      dispatch(actions.password.reset(person));
    },
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(Forgetpassword);

【问题讨论】:

    标签: reactjs react-native error-handling react-redux


    【解决方案1】:

    您需要的是一个错误边界组件,它可以捕获子节点上的所有异常并记录到服务器/通知后备屏幕。并将您的应用包装在 ErrorBoundary 组件中,以获得更少崩溃的应用。

    class ErrorBoundary extends React.Component {
         state = { hasError: false }
    
         static getDerivedStateFromError (error) {
            return { hasError: true }
         }
    
         componentDidCatch (error, info) {
            logErrorToService(error, info.componentStack)
         }
    
         render () {
            return this.state.hasError
            ? <ErrorMessageComponent />
            : this.props.children
         }
      }
    

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 2018-04-21
      • 1970-01-01
      相关资源
      最近更新 更多