gpt4 book ai didi

React组件类中的JavaScript对象函数

转载 作者:行者123 更新时间:2023-12-01 01:43:12 27 4
gpt4 key购买 nike

我在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的函数,并获取作者对象的返回值。 this.state.authors 是作者对象的数组。每个对象以authorId为键,以author对象为值。我不确定在 js 对象内声明函数时出现什么错误。希望有人能帮忙

最佳答案

这应该是方法:

articleActions = () => ({
lookupAuthor: authorId => this.state.authors[authorId]
});

关于React组件类中的JavaScript对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52217357/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com