【问题标题】:React class component setting state, getting parsing error for the "=" signReact 类组件设置状态,出现“=”符号解析错误
【发布时间】:2020-10-18 20:29:21
【问题描述】:

我正在使用带有此代码的 create-react-app(未弹出):

class App extends Component {
  state = {  
    path: 'some_string',
    organization: null,
    errors: null
  }
  componentDidMount() {
    this.onFetchFromGitHub(this.state.path);
  };
  ...

代码(应用程序)按预期工作。
但是我在 vscode 中遇到错误:

解析错误:意外令牌 = eslint [134,9]

即“=”在:

state = {` 
     /|\
      |

这是 vscode 中的突出显示。
我的理解是我可以使用这种格式而不是带有绑定的构造函数。 正如我所说,尽管出现错误,该应用仍在运行。

.eslintrc.yml

【问题讨论】:

标签: reactjs


【解决方案1】:

你使用的是哪个版本的 React?

React 在 16.8 中引入了“钩子”,它们在很大程度上取代了旧的“组件”类格式。

请看这里的介绍:https://reactjs.org/docs/hooks-intro.html

使用钩子,你上面的例子可以简化为一个函数组件:

const App = (props) => {
  // This replaces the this.state/this.setState from a component
  const [state, setState] = React.useState({  
    path: 'some_string',
    organization: null,
    errors: null
  });
  // This replaces the on mount
  React.useEffect(() => {
      onFetchFromGitHub(state.path);
  }, []);

  return ...
}

至于您的示例为什么不起作用,我认为这可能是由于您的 IDE 语法突出显示的配置所致。检查您是否安装/激活了正确的语法插件(es2015、react 等),以及您的 linter(如果有的话)是否具有正确的插件和预设。您的代码在我的 IDE 中运行良好,没有错误。

【讨论】:

    【解决方案2】:

    我通过安装 eslint 解决了这个问题。由于与 create-react-app 冲突,这给了一个问题,所以我不得不将 eslint 的 package.json 版本固定到 6.6.0,然后删除 package-lock.json 并删除 node_modules/,然后我收到了大约 30 个警告(而不是一个)。

    最后我更改了源代码以修复不必要的括号并忽略 propType 错误,最后我没有错误。

    【讨论】:

      猜你喜欢
      • 2019-02-17
      • 2018-09-04
      • 2016-12-19
      • 2020-08-12
      • 2016-09-27
      • 1970-01-01
      • 2018-10-09
      • 2010-10-01
      • 2018-01-03
      相关资源
      最近更新 更多