问题描述
每当我尝试添加类构造函数时,它都会显示此错误,意外的令牌,预期为“;”
我正在尝试使用构造函数初始化内部组件状态,但始终给出此错误。我尝试重写代码,但是没有用。
没有构造函数,一切正常,请问我想念的是什么?
我刚刚开始学习上周的反应
import React,{ Component } from 'react';
import './App.css';
function App() {
constructor(props) {
super(props);
this.state = {
list,github
};
}
const list = [
{
title: 'React',url: 'https://facebook.github.io/react/',author: 'Jordan Walke',num_comments: 3,points: 4,objectID: 0,},{
title: 'Redux',url: 'https://github.com/reactjs/redux',author: 'Dan Abramov,Andrew Clark',num_comments: 2,points: 5,objectID: 1,];
const github = [
{
id: 1,name: 'Sanusi Hayatu',username: 'hamicch',url: 'https://github.com/hamicch',repos: 24
},{
id: 2,name: 'Hayatu Michael',username: 'Azeez',url: 'https://github.com/azeez',repos: 30
},{
id: 3,name: 'Ridwan Abdulahi',username: 'ridwan',url: 'https://github.com/ridwan',repos: 50
}
];
return (
<div className="App">
{list.map(item =>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>:
<span>{item.author}</span>--
<span>{item.num_comments}</span>--
<span>{item.points}</span>
</div>
)}
<h2>GitHub Accounts</h2>
{github.map(user =>
<div key={user.id} class='acc'>
<div>
<strong>Username: </strong>
<a href={user.url}>{user.username}</a>
</div>
<div>
<strong>Name: </strong> {user.name}
</div>
<div>
<strong>Repos: </strong>
{user.repos}
</div>
</div>
)}
</div>
);
}
export default App;
解决方法
功能组件中不能包含构造函数,它仅保留给类组件。
, property: a_function
的缩写只能在对象文字或类中使用。
您不能在需要表达式或语句的地方使用它。
class Foo {
constructor() {
this.ran = Math.random();
}
}
const foo = new Foo();
const bar = new Foo();
console.log(foo.ran);
console.log(bar.ran);
您正在编写功能组件。没有类,因此您没有在构造对象,因此拥有构造函数毫无意义。