我按一个教程工作,创建了一个后端连接到mongo的全栈React Web应用程序,现在尝试将其与以前的代码合并时出现语法错误。
我尝试在Google中搜索,但没有帮助
这是我的控制台错误
module build failed(from ./node_modules/babel-loader/lib/index.js);
syntaxError: c:/users/aviram/zofim/client/src/app.js: unexpected token (49:16)
49| getDataFromDb = () => {
这是我的代码
import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
// initialize our state
constructor(props){
super(props);
this.state = {
data: [],
id: 0,
message: null,
intervalIsSet: false,
idToDelete: null,
idToUpdate: null,
objectToUpdate: null
};
this.getDataFromDb = this.getDataFromDb.bind(this);
}
// when component mounts, first thing it does is fetch all existing data in our db
// then we incorporate a polling logic so that we can easily see if our db has
// changed and implement those changes into our UI
componentDidMount() {
this.getDataFromDb();
if (!this.state.intervalIsSet) {
let interval = setInterval(this.getDataFromDb, 1000);
this.setState({ intervalIsSet: interval });
}
}
// never let a process live forever
// always kill a process everytime we are done using it
componentWillUnmount() {
if (this.state.intervalIsSet) {
clearInterval(this.state.intervalIsSet);
this.setState({ intervalIsSet: null });
}
}
// just a note, here, in the front end, we use the id key of our data object
// in order to identify which we want to Update or delete.
// for our back end, we use the object id assigned by MongoDB to modify
// data base entries
// our first get method that uses our backend api to
// fetch data from our data base
getDataFromDb = () => {
fetch('http://localhost:3001/api/getData')
.then((data) => data.json())
.then((res) => this.setState({ data: res.data }));
};
我希望它可以编译
答案 0 :(得分:0)
要解决您的问题,请将此行getDataFromDb = () => {
更改为getDataFromDb(){
。
之所以会这样,是因为您没有在构建配置中配置类属性,即babel的插件:https://babeljs.io/docs/en/babel-plugin-proposal-class-properties
请注意,该语法getDataFromDb = () => {
尚未获得批准,该提案以及有关类属性的更多信息:https://github.com/tc39/proposal-class-fields
答案 1 :(得分:0)
实际上问题出在这里,
let interval = setInterval(this.getDataFromDb, 1000);
您应该像这样调用getDataFromDb
函数,
let interval = setInterval(this.getDataFromDb(), 1000);
同样,当您使用箭头功能时,无需绑定this
,
this.getDataFromDb = this.getDataFromDb.bind(this); //You can remove this line
Demo。
注意:在这里,提取调用已更改为其他URL,以使其正常工作。
答案 2 :(得分:0)
如果使用箭头功能,则无需绑定。因此,删除this.getDataFromDb = this.getDataFromDb.bind(this);
这行就可以了。
答案 3 :(得分:0)
您忘了在结尾处填写右括号}。如果您使用的是箭头功能,则无需绑定,因此请删除此行'this.getDataFromDb = this.getDataFromDb.bind(this);'