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