我一直在尝试呈现频率最高的单词。我已经完成了获取 API。要呈现有总数的单词。我还有 setState 单词和映射的单词数组。render()
我期望单词有计数。我只得到数字1 1 1 1 1 1 1 1 1 1 1 2 1
。在表数据中。
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: []
};
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("?"));
// console.log(newPosts);
this.setState({
posts: newPosts
});
return res;
})
.then(res => {
const texts = res.data;
let words = texts.replace(/[.]/g, "").split(/\s/);
let freqMap = [];
words.map(w => {
if (!freqMap[w]) {
freqMap[w] = 0;
}
freqMap[w] += 1;
console.table(freqMap);
return freqMap;
});
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>
{this.state.words.map((post, i) => <td key={i}>{post}</td>)}
</tr>
</tbody>
</Table>
</Row>
</Col>
</Row>
</Grid>
);
}
}
export default About;