如何在定义为 ES6 类的 React 组件中使用 react-alert

IT技术 reactjs ecmascript-6
2021-05-07 05:32:17

我正在尝试在我的项目中使用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()
2个回答

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

这是一个看起来像的例子

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)

你试过这个吗?

import {alert} from 'react-alert';

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

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