[英]Line Chart data not showing
I'm trying to build a LineChart using chartjs, but I'm running through some issues with reading my data of the chart, the console.log
function of dates and coin_value returns null for some reason even though the data is transferred from the server as it should.我正在尝试使用chartjs构建一个LineChart,但是我在读取图表数据时遇到了一些问题,即使数据是从服务器传输的,日期和coin_value的
console.log
函数由于某种原因返回null正如它应该。 any idea what is the problem??知道有什么问题吗?
Here is the web page with the console right now:这是现在带有控制台的网页:
and here is my code:这是我的代码:
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;
Usestate does not have a dependency array that automatically updates, so your chartData
does never get updates. Usestate 没有自动更新的依赖数组,因此您的
chartData
永远不会得到更新。 in your fetch you need to call setChartData
already with the correct values.在您的 fetch 中,您需要使用正确的值调用
setChartData
。
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]));
setChartData({
labels: twoDimensionArr.map(item => item[0]),
datasets: [{
label: "value of BTC in ILS",
data: twoDimensionArr.map(item => item[1]),
backgroundColor: 'gold'
}]
})
})
.then(console.log(dates))
.then(console.log(coinValue))
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.