我在下面的作业中遇到了问题。
在审查以下代码时,您可能会做出哪些更改/建议进行哪些更改?
// 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,来自'react';的{Component} (缺少类名)。我可能错了。
发布于 2021-04-12 04:09:45
要创建从state data呈现列表的React组件,您需要:
React.Component的名称(在上层的CamelCase中)。您也可以尝试使用component.return状态的constructor.stats进行functional component.一个例子:
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>
    );
  }
}https://stackoverflow.com/questions/67046654
复制相似问题