简体   繁体   English

无法将 esprima 与 ReactJS 一起使用 - 意外令牌

[英]Unable to use esprima with ReactJS - Unexpected token

I am trying to parse a functions parameters with esprima in react js.我正在尝试在 react js 中使用 esprima 解析函数参数。 I am getting following error我收到以下错误

Error: Line 1: Unexpected token ( ▶ 9 stack frames were collapsed. App.render src/v4/EsprimaTest.js:12:29 9 | 10 | 11 | render() {错误:第 1 行:意外标记(▶ 9 个堆栈帧已折叠。App.render src/v4/EsprimaTest.js:12:29 9 | 10 | 11 | render() {

12 | 12 | const parsed= esprimaFB.parse(this.sum.toString()) | const 解析 = esprimaFB.parse(this.sum.toString()) | ^ 13 | ^ 13 | const parsed1= esprima.parse(this.sum.toString()) 14 | const parsed1= esprima.parse(this.sum.toString()) 14 | return ( 15 | View compiled返回 ( 15 | 查看编译

My source code is as follow.我的源代码如下。 I tried both esprima and esprima-fb我尝试了 esprima 和 esprima-fb

import React from "react";
var  esprimaFB = require("esprima-fb");
var  esprima = require("esprima");

class App extends React.Component {
  sum = (a,b)=>{
    return a+b;
}


  render() {
    const  parsed= esprimaFB.parse(this.sum.toString())
    const  parsed1= esprima.parse(this.sum.toString())
    return (
    <div>
      <div>{JSON.stringify(parsed)}</div>
      <div>{JSON.stringify(parsed1)}</div>
    </div>
    );
  }
}
export default App;

I am able to solve the problem by moving sum function outside the class.我能够通过将 sum 函数移到课外来解决这个问题。 But does not know why it did not run when it was in class scope.但是不知道为什么它在类范围内时没有运行。

import React from "react";
var  esprimaFB = require("esprima-fb");
var  esprima = require("esprima");

 const sum = (a,b)=>{
    return a+b;
}
class App extends React.Component {



  render() {

    const  parsed= esprima.parse(sum.toString())
    return (
    <div>
      <div>{JSON.stringify(parsed)}</div>

    </div>
    );
  }
}
export default App;

When you use sum inside the class, you have an arrow function.当你在类中使用sum 时,你有一个箭头函数。

Try to change:尝试改变:

esprimaFB.parse(this.sum.toString())

To:到:

esprimaFB.parse(this.sum().toString())

I don't know if the error you were getting was related to this, give it a try.我不知道您遇到的错误是否与此有关,请尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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