【问题标题】:how to throw a react-alert inside of a function in a class based component如何在基于类的组件中的函数内引发反应警报
【发布时间】:2020-02-26 03:51:52
【问题描述】:

使用 react-alert 模块进行警报 我的代码看起来像这样 - index.js:

const options = {
    // you can also just use 'bottom center'
    position: positions.TOP_CENTER,
    timeout: 5000,
    offset: '30px',
    type: types.ERROR,
    // you can also just use 'scale'
    transition: transitions.FADE
  }
ReactDOM.render(<AlertProvider template={AlertTemplate} {...options}>
    <App /></AlertProvider>, document.getElementById('root'));

App.js

class App extends React.Component { //then my state, functions, constructors,
//here is the problem
nextClicked = (e) => {
    if (//something) {
      if (//something) {

      const alert = useAlert();
      alert.show("ERROR MESSAGE!!!");
  }
} // etc
export default withAlert()(App)

基本上,我得到了错误 无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能由于以下原因之一而发生: 1. React 和渲染器的版本可能不匹配(例如 React DOM) 2. 你可能违反了 Hooks 的规则 3. 你可能在同一个应用程序中拥有多个 React 副本 有关如何调试和修复此问题的提示,请参阅 https://reactjs.org/warnings/invalid-hook-call-warning.html

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    来自their docs,它说您可以将它与更高阶的组件一起使用。所以,如果你 从 react-alert 中导入 withAlert 模块,您可以在导出时包装组件。再次,检查 github 上的文档,这已涵盖。

    将示例从文档转换为类组件,您会得到:

    import React from 'react'
    import { withAlert } from 'react-alert'
    
    class App extends React.component {
       constructor(props) {
        super(props);
      }
      render { 
      return (
      <button
        onClick={() => {
          this.props.alert.show('Oh look, an alert!')
        }}
      >
        Show Alert
      </button>
      )
     }
    }
    
    export default withAlert()(App)

    因为您将组件包装在 HOC 中,所以您可以访问 alert 属性。

    【讨论】:

    • 我尝试更改代码以将导出默认类 App 包装为 withAlert()(App) 并使用类 App extends React.Component ({ alert }) => { 定义 App,这给出了一个语法错误。我不确定如何定义应用程序以便发出警报。同样,文档包装了 App,然后它是一个基于函数的组件
    • 您可以编辑您的问题以显示它现在的样子吗?只要您不使用钩子,就可以使用类组件。实现没有什么需要改变,你只是不能在类组件中使用钩子
    • 语法错误是箭头。声明类组件时不要使用箭头函数
    • 仍然不清楚要更改什么才能使其正常工作,我删除了对类 App 声明所做的更改以删除语法错误,但随后警报未定义
    • 没有看到你的整个应用组件,现在的样子,我无法告诉你你需要改变什么
    猜你喜欢
    • 2021-12-09
    • 2019-05-26
    • 2022-11-07
    • 2021-03-08
    • 2020-07-31
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多