我尝试使用chartjs构建一个LineChart,但是我在阅读图表数据时遇到了一些问题,日期和coin_value的console.log
函数由于某种原因返回了null,尽管数据是从服务器传输过来的。知道问题是什么吗?
下面是当前包含控制台的网页:
下面是我代码:
import { Link } from "react-router-dom";
import { Line } from "react-chartjs-2";
import {Chart as chartjs, Title, Tooltip, LineElement, Legend, CategoryScale, LinearScale, PointElement} from "chart.js";
chartjs.register(
Title, Tooltip, LineElement, Legend, CategoryScale, LinearScale, PointElement
)
function BitCoin() {
const [data, setData] = React.useState(null);
const [dates, setDates] = React.useState(null);
const [coinValue, setCoinValue] = React.useState(null);
React.useEffect(() => {
fetch("http://localhost:3001/bitcoin")
.then((res) => res.json())
.then((data) => {
const twoDimensionArr = data.message;
setData(twoDimensionArr);
setDates(twoDimensionArr.map(item => item[0]));
setCoinValue(twoDimensionArr.map(item => item[1]));
})
.then(console.log(dates))
.then(console.log(coinValue))
}, []);
const [chartData, setChartData] = useState({
labels: dates,
datasets: [{
label: "value of BTC in ILS",
data: coinValue,
backgroundColor: 'gold'
}]
}, [data])
return (
<div style={{textAlign:"center", fontFamily:"Comic Sans MC", fontSize:"100"}}>
THIS IS THE BitCoin PAGE
<nav>
<Link to="/"> Home </Link>
</nav>
<nav>
<Link to="/coins"> Coins </Link>
</nav>
<Line
data = {chartData}
/>
</div>
)
}
export default BitCoin;
1条答案
按热度按时间2ekbmq321#
Usestate没有一个自动更新的依赖数组,所以你的
chartData
永远不会得到更新。在你的提取中,你需要用正确的值调用已经存在的setChartData
。