我嘗試使用從服務器獲取的資料渲染 visx wourdcloud。我用于顯示網站的組件如下:
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { withRouter, RouteComponentProps, useParams } from 'react-router';
import WordCloud from '@/components/WordCloud';
import { getAggregations } from '@/selectors';
export interface WordData {
text: string;
value: number;
}
const AggregationShowComponent: React.FC<RouteComponentProps> = ({ history }) => {
const dispatch = useDispatch();
const { id }: { id: string } = useParams();
const { loading, aggregations } = useSelector(getAggregations);
const aggregation = aggregations.find(a => a._id == id);
const words = [
{
text: 'a',
value: 228
},
{
text: 'b',
value: 42
},
];
if (loading) {
return (
<div>Loading</div>
)
}
return (
<div>
{aggregation._id}
<WordCloud
words={aggregation.data}
// words={words}
width={1024}
height={600}
spiral="archimedean"
rotate="0"
/>
<p>
{aggregation.name}
</p>
</div>
)
}
export const AggregationShow = withRouter(AggregationShowComponent);
負責渲染 wordcloud 的組件如下:
import React, { useState, useEffect } from 'react';
import { Text } from '@visx/text';
import { scaleLog } from '@visx/scale';
import { Wordcloud } from '@visx/wordcloud';
type SpiralType = 'archimedean' | 'rectangular';
export interface WordData {
text: string;
value: number;
}
interface WordCloudProps {
width: number;
height: number;
words: WordData[],
rotate: number,
spiral: SpiralType,
colors: String[],
}
const colors = ["#000000", "#aaaaaa", '#bbbbbb'];
const fixedValueGenerator = () => 0.5;
export default function WordCloud({ words, width, height, rotate = 0, spiral = 'archimedean' }: WordCloudProps) {
const fontScale = scaleLog({
domain: [Math.min(...words.map((w) => w.value)), Math.max(...words.map((w) => w.value))],
range: [10, 100],
});
const fontSizeSetter = (datum: WordData) => fontScale(datum.value);
return (
<>
<Wordcloud
words={words}
width={width}
height={height}
fontSize={fontSizeSetter}
font={'Impact'}
padding={2}
spiral={spiral}
rotate={rotate}
random={fixedValueGenerator}
>
{(cloudWords) =>
cloudWords.map((w, i) => (
<Text
key={w.text}
fill={colors[i % colors.length]}
textAnchor={'middle'}
transform={`translate(${w.x}, ${w.y}) rotate(${w.rotate})`}
fontSize={w.size}
fontFamily={w.font}
>
{w.text}
</Text>
))
}
</Wordcloud>
</>
);
}
如果我嘗試使用請求中的資料(在aggregation.data 中找到),我會在 d3.js 中收到以下錯誤:

當我在第一個代碼塊中注釋掉的行中使用簡單的靜態資料時,它可以正常作業。只有當我嘗試在 wordcloud 中使用來自 http 請求的資料時,才在當前資料正常作業時獲取和顯示整個資料,我收到錯誤。
我還嘗試克隆傳遞到 wordcloud 組件中的資料,以確保某些 redux saga 對狀態的影響不會導致錯誤,但錯誤保持不變。此外,我還嘗試使用 useEffect 等重置資料,但仍然沒有成功。
我缺少什么部分?react/d3 的某些部分是否會導致我不知道的這個問題?有沒有辦法規避這個問題?
謝謝
uj5u.com熱心網友回復:
我找到了解決方案。d3-cloud 修改了 words 陣列,這與 redux 存盤資料的可變性相沖突。我只是創建了一個陣列的深層副本:
.data.map(w = {...w})
不確定庫的任何其他部分是否應該阻止編輯資料,但這對我有用!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/325992.html
標籤:javascript 反应 d3.js redux-saga 可视化
上一篇:附加標簽未出現在圖表d3.js中
