简体   繁体   中英

ReactJS - Can not return jsx for callback function?

I have been working with react for a while but I got to very basic problem but I don't understand why it doesn't work. Basically, in Login component I submit a form and when it return an error, render a snackbar message.

  handleSubmit = (event) => {
    event.preventDefault()
  //api call here
    onFormSubmit(this.state)
     .then(() => history.push('/teams'))
     .catch(e => <Snackbar message={e}/>)
  }

  render() {

Console shows no errors but I don't see any snackbar when the onFormSubmit call fails.

Update

I understand now, I didn't place Snackbar inside render () { return (.... I can think of the only way to do it like that:

this.state = {
  email: '',
  password: '',
  error: ''
}
handleSubmit = (event) => {
event.preventDefault()
//api call here
onFormSubmit(this.state)
 .then(() => history.push('/teams'))
 .catch(e => this.setState({error: e})
}
render () {
 return (
   <div>
      {this.state.error && <Snackbar message={this.state.error}/>}....

But I don't want to submit also the error field to server. Is there another way to inject it to component?

your solution is correct, you can also delegate the handleSubmit to the parent component, then if you have an error you display the Snackbar component otherwise you display the Form component.

In your example, if you don't want to post the error, you can destructure the state object to control the properties you want to send.

handleSubmit = (event) => {
  const {email, password} = this.state;
  event.preventDefault()
  //api call here

  onFormSubmit({email, password})
    .then(() => history.push('/teams'))
    .catch(e => this.setState({error: e})
}

You will need to place that component into rendered JSX, or inject it somehow. Are you calling handleSubmit inside of your render's return?

One option is to use JQuery inside of that catch to inject that Snackbar onto the page.

A better option is to somehow trigger that component inside of your render's return like normal. For instance, set a localState variable of error to true inside of the catch, and then render the snackbar conditionally inside of your render based off this.state.error being true.

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