我在react组件中使用了对象函数,下面是我的代码,我试图在articleActions对象内创建一个对象函数,没有语法错误。 api导入工作正常,我获取了正确的数据并存储在以下组件状态:this.state.articles,this.state.authors。
App.js
import React from "react";
import DataApi from "../DataApi";
import data from "../testData";
import ArticleList from "./ArticleList";
const api = new DataApi(data.data);
class App extends React.Component {
constructor() {
super();
this.state = {
articles: api.getArticles(),
authors: api.getAuthors()
};
}
articleActions = {
lookupAuthor: authorId => this.state.authors[authorId]
};
render() {
return (
<ArticleList
articles={this.state.articles}
articleActions={this.articleActions}
/>
);
}
}
export default App;
第二个文件:ArticleList.js
import React from "react";
import Article from "./Article";
const ArticleList = props => {
return (
<div>
{Object.values(props.articles).map(article => (
<Article
key={article.id}
article={article}
actions={props.articleActions}
/>
))}
</div>
);
};
export default ArticleList;
第三个文件:Article.js
import React from "react";
const Article = props => {
const { article, actions } = props;
const author = actions.lookupAuthor(article.authorId);
return (
<div>
<div>{article.title}</div>
<div>{article.date}</div>
<div>
<a href={author.website}>
{author.firstName} {author.lastName}
</a>
</div>
<div>{article.body}</div>
</div>
);
};
export default Article;
错误消息是:
SyntaxError: C:/Users/coral/Documents/react-advanced/lib/components/App.js:
Unexpected token (16:17)
14 | };
15 | }
> 16 | articleActions = {
| ^
17 | lookupAuthor: authorId => this.state.authors[authorId]
18 | };
lookupAuthor应该是带有参数:authorId的函数,并获取author对象的返回值。 this.state.authors是作者对象的数组。每个以authorId为键,而author对象为值的对象。我不确定在js对象中声明函数时这里的错误是什么。希望有人能帮忙
答案 0 :(得分:2)
应该是方法:
articleActions = () => ({
lookupAuthor: authorId => this.state.authors[authorId]
});