我一直在与React合作一段时间,但是我遇到了一个非常基本的问题,但我不明白为什么它不起作用。
基本上,在“登录”组件中,我提交一个表单,当它返回错误时,呈现一个快餐栏消息。

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

  render() {


在onFormSubmit调用失败时,控制台没有显示任何错误,但我看不到任何小吃栏。

更新资料

我现在知道了,我没有将Snackbar放在render(){return(....
我可以想到这样的唯一方法:

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}/>}....


但是我也不想将错误字段提交给服务器。还有另一种方法可以将其注入组件吗?

最佳答案

您将需要将该组件放入渲染的JSX中,或以某种方式注入它。您是否在渲染返回中调用handleSubmit

一种选择是在该捕获中使用JQuery将Snackbar注入页面。

更好的选择是以某种方式像正常情况一样在渲染返回中触发该组件。例如,将catch内的localState变量error设置为true,然后根据this.state.error为true来有条件地在渲染器内部渲染小吃栏。

关于javascript - ReactJS-无法为回调函数返回jsx吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54262234/

10-09 07:47
查看更多