You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件词频渲染异常求助:仅显示数字无对应单词

问题分析与解决方案

嘿,我一眼就看出问题所在了——你表格里只显示词频数字,看不到对应单词,主要是两个核心原因:

1. 词频存储用错了数据结构

你把freqMap定义成了数组[],但实际上应该用**对象{}**来存储词频。数组的键是数字索引,当你用单词作为键(比如freqMap["hello"] = 1)时,这些单词会变成数组的“额外属性”,而非数组的正式元素。之后你用map遍历this.state.words的时候,只能遍历到那些数字索引的元素(也就是你看到的一串1、2),根本拿不到对应的单词。

2. 渲染时只输出了词频值

就算存储逻辑正确,你当前的渲染代码也只输出了词频数值,没有把对应的单词一起展示出来。


修正步骤

第一步:把词频存储改成对象

将let freqMap = [];替换成let freqMap = {};,其余统计词频的逻辑不用变,因为对象同样支持freqMap[w]的访问方式。

第二步:过滤空字符串(可选但推荐)

文本拆分后可能会产生空字符串,记得过滤掉避免无效统计:

let words = texts.replace(/[.]/g, "").split(/\s/).filter(word => word.trim() !== '');

第三步:修改渲染逻辑,同时展示单词和词频

用Object.entries()把对象转成键值对数组,这样就能同时获取单词和对应的词频:

{Object.entries(this.state.words).map(([word, count], i) => (
  <tr key={i}>
    <td>{word}</td>
    <td>{count}</td>
  </tr>
))}

修正后的完整代码

import React, { Component } from "react";
import { Grid, Row, Col, Table } from "react-bootstrap";
import axios from "axios";

class About extends Component {
  state = { counts: [], posts: [], words: {} }; // 初始化words为对象

  componentDidMount() {
    axios({
      url: "https://cors-anywhere.herokuapp.com/http://terriblytinytales.com/test.txt",
      responseType: "text"
    })
      .then(res => {
        const posts = res.data;
        const newPosts = posts.split(/[0-9]+\./).map(post => post.split("?"));
        this.setState({ posts: newPosts });
        return res;
      })
      .then(res => {
        const texts = res.data;
        // 过滤空字符串,避免统计无效内容
        let words = texts.replace(/[.]/g, "").split(/\s/).filter(word => word.trim() !== '');
        let freqMap = {}; // 改用对象存储词频
        words.forEach(w => { // 用forEach更合适,无需返回值
          if (!freqMap[w]) {
            freqMap[w] = 0;
          }
          freqMap[w] += 1;
        });
        this.setState({ words: freqMap });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <Grid>
        <Row>
          <Col xs={12} sm={6} md={6}>
            <h1>fetched data</h1>
            <ol>
              {this.state.posts.map((post, i) => (
                <li key={i} style={{ listStyle: "none" }}>
                  {post.map((p, j) => (
                    <p key={j}>{p + (j % 2 === 0 ? "?" : "")}</p>
                  ))}
                </li>
              ))}
            </ol>
          </Col>
          <Col xs={12} sm={6} md={6}>
            <Row>
              <Table striped bordered condensed hover>
                <tbody>
                  <tr>
                    <th>单词</th>
                    <th>词频</th>
                  </tr>
                  {/* 转成键值对数组,同时渲染单词和词频 */}
                  {Object.entries(this.state.words).map(([word, count], i) => (
                    <tr key={i}>
                      <td>{word}</td>
                      <td>{count}</td>
                    </tr>
                  ))}
                </tbody>
              </Table>
            </Row>
          </Col>
        </Row>
      </Grid>
    );
  }
}

export default About;

这样修改后,表格就能正确显示每个单词和它对应的词频了~

内容的提问来源于stack exchange,提问作者amar ghodke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:48:05