【问题标题】:React.js 'Unexpected token' < when using form tagReact.js 'Unexpected token' < 使用表单标签时
【发布时间】:2017-03-04 17:10:32
【问题描述】:

我一直在使用带有 babel、webpack、redux 和 semantic-ui-react 的 mern stack 制作一个 Web 应用程序。

但我收到一个错误提示

"unexpected token

仅当我单击表单标签中的按钮发送请求时才会发生此错误。如果我制作的页面没有表单标签,它可以正常工作,没有任何错误。

这是我在 React 中的代码。

handleUpload(title, contents, userId) {
  return this.props.createPostRequest(title, contents, userId).then(
    () => {
      if(this.props.post.status === 'SUCCESS') {
        alert('Your post is saved successfully.');
        browserHistory.push('/');
        return true;
      } else {
        alert('Save Fail: ' + this.props.post.failReason);
        return false;
      }
    }
  );
}

render() {
  return(
    <div className="Write">
      <br/>
      <br/>
      <Form>
        <Container text>
          <Form.Input label='Title' fluid name='title' placeholder='title'
            value={this.state.title} onChange={this.handleChange}>
            <input/>
          </Form.Input>
          <Form.TextArea rows='20' name='contents' placeholder='Write here!'
            value={this.state.contents} onChange={this.handleChange}>
            <textarea/>
          </Form.TextArea>
          <br/>
          <Button.Group>
            <Button color='orange' as={Link} to='/'>Cancel</Button>
            <Button.Or/>
            <Button positive onClick={this.handleUpload}>Save</Button>
          </Button.Group>
        </Container>
      </Form>
    </div>
  );
}

当我输入字母并点击保存按钮时,我会看到一条警告消息说

您的帖子已成功保存..

我放的数据也保存在mongodb中。但是在我点击确定后,网址从'localhost:3000/post/write'变为'localhost:3000/post/write?title=blah&amp;contents=blah'。 url中的blah是我在输入标签中输入的内容。然后控制台说

意外的令牌<.>

但是,如果我在上面的代码中不使用表单标签,它可以正常工作,我完全不知道有什么问题。表单标签来自语义-ui-react。所以我需要它。如果我不使用Form,它会工作得很好,但我应该放弃semantic-ui提供的设计。

有人知道吗?我想这与表单标签中的 HTTP POST 有关,这使 react.js 在服务器端处理来自该表单标签的发布请求后无法理解 index.html 中的 bundle.js。

【问题讨论】:

  • 你也在使用 redux 吗?
  • 您描述的 URL 行为是一个没有指定 method="post" 的表单(它使用 GET 的默认表单提交,它将值发布到查询字符串)。
  • @MohammadMustaqeem 是的,我是。
  • @RobWilkins 正如你所说,我在表单标签中尝试了 method="post",然后控制台显示“无法 POST /post/write”

标签: javascript reactjs webpack babeljs semantic-ui-react


【解决方案1】:

TL;DR

handleSubmit = (e) => e.preventDefault()

<Form onSubmit={this.handleSubmit} />

为什么?

默认情况下,HTML 表单会在提交时向当前 URI 发出 GET 请求,请参阅here。同样默认情况下,表单中的按钮将提交它:

http://codepen.io/levithomason/pen/RpEwWP

<form onsubmit="alert('submitted!')">
  <button>I'll submit</button>
  <button>Me too</button>
</form>

正在发生的事情是,React 正在渲染一个 &lt;form /&gt;,其中包含一些 &lt;button /&gt;s,当您单击它们时,它正在使用表单数据向当前 URI 发出 GET 请求。

我敢打赌,为您的应用程序提供服务的本地服务器没有处理程序来接受此请求。更进一步,我敢打赌它还有一个回退,可以在未知请求上以 index.html 响应。这对于单页应用程序来说是司空见惯的,它允许应用程序的软路由器而不是服务器来处理路由。这可能导致您对bundle.js 的请求实际上收到了index.html,因此出现了意外令牌。

既然你说:

...如果我在上面的代码中不使用表单标签,它可以正常工作...

只需阻止表单提交即可为您解决。

【讨论】:

  • 抱歉,回答迟了。谢谢!现在可以正常使用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2012-01-31
相关资源
最近更新 更多