componentDidMount 中存在我无法解决的语法错误
There is a syntax error in componentDidMount that I cannot resolve
我正在为我制作的 API 创建一个前端,我正在使用 React 作为前端。当我尝试使用 componentDidMount(){}
时,我收到一个语法错误,提示应为 ;
。 ;
应介于 )
和 {
之间。
似乎是什么问题?
P.S。我正在使用 visual studio 代码 - 探索
我尝试插入分号,但这导致了更多问题。
import React from 'react';
import './App.css';
function App() {
state = {
students: []
}
componentDidMount(){
this.getStudents();
}
getStudents = _ => {
fetch('http://localhost:4000/students')
.then(response => response.json())
.then(response => this.setState({students: response.data}))
.catch(err => console.error(err))
}
renderStudent = ({student_id, name}) => <div key={student_id}>{name}</div>
return (
<div className="App">
{students.map(this.renderStudent)}
</div>
);
}
export default App;
您正在将 class 语法混合到声明为函数的组件中。 componentDidMount 是 class 组件上的一个方法。因此,即使在它之前添加函数来解决您的语法问题,也不会为您提供所需的结果。
With函数使用hooks,或者切换到
基于 class 的组件。
componentDidMount()
是一个 React 组件 API,而您使用的是一个没有此 API 的功能组件。
有效..我将函数 App () 更改为 class App extends Component。
感谢您的帮助。
我正在为我制作的 API 创建一个前端,我正在使用 React 作为前端。当我尝试使用 componentDidMount(){}
时,我收到一个语法错误,提示应为 ;
。 ;
应介于 )
和 {
之间。
似乎是什么问题?
P.S。我正在使用 visual studio 代码 - 探索
我尝试插入分号,但这导致了更多问题。
import React from 'react';
import './App.css';
function App() {
state = {
students: []
}
componentDidMount(){
this.getStudents();
}
getStudents = _ => {
fetch('http://localhost:4000/students')
.then(response => response.json())
.then(response => this.setState({students: response.data}))
.catch(err => console.error(err))
}
renderStudent = ({student_id, name}) => <div key={student_id}>{name}</div>
return (
<div className="App">
{students.map(this.renderStudent)}
</div>
);
}
export default App;
您正在将 class 语法混合到声明为函数的组件中。 componentDidMount 是 class 组件上的一个方法。因此,即使在它之前添加函数来解决您的语法问题,也不会为您提供所需的结果。
With函数使用hooks,或者切换到 基于 class 的组件。
componentDidMount()
是一个 React 组件 API,而您使用的是一个没有此 API 的功能组件。
有效..我将函数 App () 更改为 class App extends Component。 感谢您的帮助。