我正在为我制作的API创建一个前端,我将React用作前端。当我尝试使用componentDidMount(){}
时,我会发现一个语法错误,上面说明;
。预计;
和{
之间的CC_3。似乎是什么问题?
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;
您将类语法混合到称为函数的组件中。ComponentDidMount是类组件上的一种方法。因此,即使在它之前添加函数(可以解决您的语法问题(,也不会给您您所寻找的结果。
使用功能使用钩子,或切换到基于类的组件。
componentDidMount()
是一种反应组件API,而您使用的是不使用此API的函数组件。
它工作了..我将函数应用程序((更改为类应用程序扩展了组件。感谢您的帮助。