所以我正在尝试使用名为 react-alert 的库进行错误处理。
我使用 Axios 作为我的 REST 处理程序。我创建了一个动作和一个减速器,它们都工作正常;当我提出发布请求时,在我的 DevTools 扩展中看到了我的状态更新。
这是我名为 Alert.js 的功能组件
import React, { Fragment, useState } from "react";
import { useAlert } from "react-alert";
import { useSelector } from "react-redux";
import { useEffect } from "react";
export default function Alert(props) {
const alert = useAlert();
const error = useSelector((state) => state.errors.errors);
const [errorMSG, setERRORS] = useState();
useEffect(() => {
if (error !== errorMSG) {
setERRORS(error);
alert.show(errorMSG);
} else {
alert.show("Welcome!");
}
}, [errorMSG]);
return <Fragment />;
然后我在我的主 App.js 中调用它
//Main Imports
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
// React Alert
import { Provider as AlertProvider } from "react-alert";
import AlertTemplate from "react-alert-template-basic";
import Alert from "./layout/Alert";
const alertOptions = {
timeout: 3000,
position: "top center",
};
//Components import
import Header from "./layout/Header";
import Dashboard from "./products/Dashboard";
//Redux import
import { Provider } from "react-redux";
import store from "../store";
class App extends Component {
render() {
return (
<Provider store={store}>
<AlertProvider template={AlertTemplate} {...alertOptions}>
<Alert />
<Fragment>
<Header />
<div className="container-fluid">
<Dashboard />
</div>
</Fragment>
</AlertProvider>
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
我确实看到了欢迎!当应用程序安装时,但当我出现错误时,我什么也看不到。谁能帮我找到解决办法;将不胜感激。
答案 0 :(得分:2)
您看到“欢迎”是因为当您的组件第一次挂载时,它会调用 useEffect
钩子。但是由于为 useEffect
提供了错误的依赖项,之后 useEffect
钩子没有被触发。您需要添加 error
而不是 errorMSG
,因为 error
来自您的 store
,并且您希望在发出新的 error
时显示该消息:
useEffect(() => {
if (error !== errorMSG) {
setERRORS(error);
alert.show(errorMSG);
} else {
alert.show("Welcome!");
}
}, [error]);