【问题标题】:How to use react-alert with React component that is defined as ES6 class如何将 react-alert 与定义为 ES6 类的 React 组件一起使用
【发布时间】:2020-01-18 09:19:37
【问题描述】:

我正在尝试在我的项目中使用https://www.npmjs.com/package/react-alert,但是这些示例是为声明为函数的 React 组件提供的,但我的 React 组件被声明为如下类:

class ConnectedOrderForm extends Component {

    //const statusAlert = useAlert();

    constructor(props) {
        super(props);
    }

   render() {
        return (
            <div>Test</div>
        )
   }
}

const OrderForm = withRouter(connect(mapStateToProps, mapDispatchToProps)(ConnectedOrderForm));
export default OrderForm;

当我尝试从课堂活动中调用 useAlert().show('OK'); 时,我得到:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

那么,我该如何使用 ES6 类组件中的这个 react-alert 钩子呢?

解决方案是使用任一导出代码:

const OrderForm = withRouter(connect(mapStateToProps, mapDispatchToProps)(ConnectedOrderForm));
export default withAlert()(OrderForm);

const OrderForm = withAlert()(withRouter(connect(mapStateToProps, mapDispatchToProps)(ConnectedOrderForm)));
export default OrderForm;

然后调用:

this.props.alert.show()

【问题讨论】:

标签: reactjs ecmascript-6


【解决方案1】:

你试过这个吗?

import {alert} from 'react-alert';

alert.show('Some message', {
  ... options
})

UPD。对不起,这是错误的答案,请看这里: https://github.com/schiehll/react-alert/issues/116

【讨论】:

  • 当然不行,因为react-alert不会导出alert。
  • 对不起,有一个已关闭的问题:github.com/schiehll/react-alert/issues/116
  • Thx,该链接有所帮助,但我必须接受另一个更明确的答案。谢谢。
【解决方案2】:

根据文档,您似乎不应该使用 useAlert 钩子,而应该使用 withAlert HOC。 Hooks 只能用在函数式组件中,既然要使用类,就需要withAlert HOC。

这是一个看起来像的例子

import { withAlert } from 'react-alert'

class App extends React.Component {
  render() {
    const alert = this.props.alert;
    return (
      <button
        onClick={() => {
         alert.show('Oh look, an alert!')
        }}
       >
        Show Alert
      </button>
    );
  }
}

export default withAlert()(App)

【讨论】:

  • 投掷错误:Error: Objects are not valid as a React child (found: object with keys {code, message}). If you meant to render a collection of children, use an array instead......
猜你喜欢
  • 2021-08-11
  • 1970-01-01
  • 2021-04-07
  • 2021-05-22
  • 2019-05-16
  • 2019-07-31
相关资源
最近更新 更多