因此,我编写了一些代码来显示图表,并且还编写了一个函数,可以让我更改图表的时间范围。但是,当调用此函数时,会弹出一个重复的图表。
这是Chart.js
let chartProperties = {
width: 1000,
height: 500,
timeScale: {
timeVisible: true,
secondsVisible: false
}
}
const Chart = (props) => {
useEffect(() => {
fetchData()
}, [])
const lightweightChart = createChart(document.body, chartProperties);
const candleSeries = lightweightChart.addCandlestickSeries();
const fetchData = () => {
axios.get(`https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1m&limit=1000`)
.then(response => response.data)
.then(data => {
const candlestickData = data.map(d => {
return { time: d[0] / 1000, open: parseFloat(d[1]), high: parseFloat(d[2]), low: parseFloat(d[3]), close: parseFloat(d[4]) }
});
candleSeries.setData(candlestickData);
}).catch(error => console.log(error))
}
return (
<div>
</div>
);
}
const mapStateToProps = (state) => {
return {
chartData: state.chartOptionsReducer
}
}
export default connect(mapStateToProps)(Chart);
这是动作创建者chartActions.js
export const changeTimeframe = (timeframe) => {
return {
type: 'CHANGE_TIMEFRAME',
payload: {
timeframe: timeframe
}
}
}
这是reducer chartOptionsReducer.js
const initState = {
symbol: 'BTCUSDT',
timeframe: '4h'
}
const chartOptionsReducer = (state = initState, action) => {
console.log(action)
if (action.type === 'CHANGE_TIMEFRAME') {
let newTimeframe = action.payload.timeframe
return {
...state,
timeframe: newTimeframe
}
} else {
return state;
}
}
export default chartOptionsReducer;
最后,这是从OptionsColumn.js调用操作的地方
const OptionColumn = (props) => {
const handleTimeframe = (timeframe) => {
props.changeTimeframe(timeframe)
}
return (
<Menu
label="Timeframe"
items={[
{ label: '1m', onClick: () => { handleTimeframe('1m') } },
{ label: '4h', onClick: () => { handleTimeframe('4h') } },
]}
/>
)
}
const mapDispatchToProps = (dispatch) => {
return {
changeTimeframe: (timeframe) => { dispatch(changeTimeframe(timeframe)) }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(OptionColumn);
我认为问题可能来自Chart.js中的这一行,虽然我不确定,我也不知道如何避免它:
const lightweightChart = createChart(document.body, chartProperties);
奖励问题:任何熟悉轻量级图表包的人,有没有办法在容器中而不是 document.body 中显示图表?谢谢