简体   繁体   中英

react.js - react-alert - Uncaught Invariant Violation: Invalid hook call

I have this piece of code in my react.js application :

import { withAlert} from "react-alert";
 class Signup extends React.Component {
state={email:'',passwordHash:'',rePasswordHash:''};
onButtonClick = () =>{
    if(this.state.passwordHash!==this.state.rePasswordHash){
        this.props.alert.error("Wrong password");
    }
    else{
        this.props.alert.show("Creating new account");
    }
};
render(){
    return(
                    <ButtonActor name="Sign In" onButtonClick={this.onButtonClick} />
    );
}
}
export default withAlert()(Signup);

It's in my SignUp class, whenever user try to create account, it just takes password entered in both fields are same or not. According to that it should create an alert. But it is crashing and gives me this error:

Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component.

react-alert , the library I'm using.

Can anyone help me how can I resolve this?

If you are using class component, then:

import { withAlert } from "react-alert";
...
export default withAlert()(Home)

and call it as:

this.props.alert.show()

I just wrapped <App/> with <AlertProvider/> .

Sample from doc, now they have better doc :

// index.js
import React from 'react'
import { render } from 'react-dom'
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'
import App from './App'

// optional cofiguration
const options = {
  // you can also just use 'bottom center'
  position: positions.BOTTOM_CENTER,
  timeout: 5000,
  offset: '30px',
  // you can also just use 'scale'
  transition: transitions.SCALE
}

const Root = () => (
  <AlertProvider template={AlertTemplate} {...options}>
    <App />
  </AlertProvider>
)

render(<Root />, document.getElementById('root'))

And this one :

// App.js
import React from 'react'
import { useAlert } from 'react-alert'

const App = () => {
  const alert = useAlert()

  return (
    <button
      onClick={() => {
        alert.show('Oh look, an alert!')
      }}
    >
      Show Alert
    </button>
  )
}

They have interface for button too :

import React from 'react'
import { withAlert } from 'react-alert'

const App = ({ alert }) => (
  <button
    onClick={() => {
      alert.show('Oh look, an alert!')
    }}
  >
    Show Alert
  </button>
)

export default withAlert()(App)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM