首页 > 解决方案 > 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'; (缺少类名)。我可能是错的。

标签: javascriptreactjs

解决方案


要创建一个从状态数据呈现列表的 React 组件,您需要:

  1. 修复组件:给它一个扩展的名称(在骆驼大写中)React.Component。您也可以尝试功能组件。
  2. 在构造函数stats初始化状态数据。
  3. 在块中使用JSX渲染列表。return

一个例子:

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>
    );
  }
}

推荐阅读