【问题标题】:React-alert library does not seem to be re-rendering when state changes状态更改时,React-alert 库似乎没有重新渲染
【发布时间】:2021-05-15 21:15:44
【问题描述】:

所以我正在尝试使用一个名为 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"));

我确实看到了欢迎!当应用程序安装时,但当我有错误时,我什么也看不到。任何人都可以帮我找到解决方案吗?将不胜感激。

【问题讨论】:

  • 组件的本地状态出现错误有什么意义?
  • 什么都没有。只是我尝试了不同的事情,因为我找不到解决方案,但现在我正在使用 Redux 存储状态,它工作得很好!

标签: javascript reactjs redux react-redux axios


【解决方案1】:

您会看到“欢迎”,因为当您的组件第一次安装时,它会调用 useEffect 挂钩。但是由于为useEffect 提供了错误的依赖项,useEffect 钩子之后没有被触发。您需要添加error 而不是errorMSG,因为error 来自您的store,并且您希望在发出新的error 时显示该消息:

 useEffect(() => {
    if (error !== errorMSG) {
      setERRORS(error);
      alert.show(errorMSG);
    } else {
      alert.show("Welcome!");
    }
  }, [error]);

【讨论】:

  • 成功了!太感谢了!我不需要使用本地状态的一件事,我的错误是;不遍历状态产生的对象。
猜你喜欢
  • 2018-11-29
  • 2020-10-03
  • 1970-01-01
  • 2021-11-24
  • 2019-02-27
  • 2020-04-13
  • 1970-01-01
  • 2018-04-14
  • 2019-09-23
相关资源
最近更新 更多