javascript - React.js:在输入现有统计数据和有关投票的统计数据后计算新的统计数据
问题描述
我在下面的这个任务中遇到了麻烦。
查看以下代码时,您可能会做出/建议哪些更改?
// utils/stats.js
export const voteStats = (votes, existingStats) => {
if (!Array.isArray(votes)) {
throw new Error('You must pass an array of votes to voteStats');
}
const ret = [];
for (const v of votes) {
const hash = {};
hash.count = v.count;
hash.userId = v.user.id;
ret.push(hash);
}
for (const stat of existingStats) {
ret.push(stat);
}
return ret;
};
// utils/stats-test.js
import { voteStats } from './stats';
describe('voteStats', () => {
it('should calculate new stats after being fed existing stats and stats about votes', () => {
expect(
voteStats(
[
{ count: 22, user: { id: 121 } },
{ count: 61, user: { id: 122 } },
{ count: 93, user: { id: 123 } },
],
[
{ count: 11, userId: 118 },
{ count: 42, userId: 119 },
{ count: 78, userId: 120 },
]
)
).toEqual([
{ count: 11, userId: 118 },
{ count: 42, userId: 119 },
{ count: 78, userId: 120 },
{ count: 22, userId: 121 },
{ count: 61, userId: 122 },
{ count: 78, userId: 123 },
]);
});
});
// user-actions.js
import { voteStats } from './utils/stats';
export default class {
constructor(votes = [], stats = []) {
this.stats = voteStats(votes, stats);
}
render() {
return `<ul>
${this.stats.map(
stat => `<li>User ID ${stat.userId} took ${stat.count} actions</li>`
)}
</ul>`;
}
}
我是学习 React 的新手,无法理解代码分配的情况。对我来说,我可以在 //user.actions.js 文件中看到它丢失了
-import React, {Component} from 'react'; (缺少类名)。我可能是错的。
解决方案
要创建一个从状态数据呈现列表的 React 组件,您需要:
一个例子:
import { Component } from "react";
import { voteStats } from './utils/stats';
const votes = [{ count: 22, user: { id: 121 } }, { count: 61, user: { id: 122 } }, { count: 93, user: { id: 123 } },];
const existingVotes = [{ count: 11, userId: 118 }, { count: 42, userId: 119 }, { count: 78, userId: 120 },];
export default class UserActions extends Component { // 1
constructor(props) {
super(props);
this.state = {
stats: voteStats(votes, existingVotes), // 2
};
}
render() {
// 3
return (
<ul>
{this.state.stats.map((stat) => (
<li key={stat.userId}>
User ID {stat.userId} took {stat.count} actions
</li>
))}
</ul>
);
}
}
推荐阅读
- reactjs - 组件未显示
- javascript - 在类中使用异步等待来分配属性但返回 null
- reactjs - 将自定义道具与 RouteComponentProps 组合时缺少位置、历史和匹配属性
- asp.net-core - 如何使用 OpenIdConnect 身份验证登录 ASP.NET Core 身份用户?
- ckan - 是否可以在 CKAN Data Explorer 默认预览中隐藏 _id 列?
- jquery - JqueryUI 数据表设置记录总数
- c - 为什么 C 文件流的开头称为“SEEK_SET”?
- php - jQuery ajax 响应返回格式化的 HTML
- amazon-web-services - 在 Terraform 中使用已创建资源的最佳实践是什么?
- ruby-on-rails - Rails 6 使用 bundler 2 部署到 Heroku,但仍然卡顿