因此,我已经编写了一些代码来显示图表,并且还编写了一个函数,它允许我更改图表的时间框架。但是,当调用此函数时,会弹出一个重复的图表。
这是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);
下面是action creator chartactions.js
export const changeTimeframe = (timeframe) => {
return {
type: 'CHANGE_TIMEFRAME',
payload: {
timeframe: timeframe
}
}
}
这是reducer图表选项reducer.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);
额外问题:任何熟悉lightweightchart包的人,有没有办法在容器中显示图表而不是document.body?谢谢
1条答案
按热度按时间u1ehiz5o1#
在react中,组件将在某些条件下重新渲染,包括道具更改。
每当chart.js重新呈现时,下面的代码将重新运行(它将创建新的图表)
document.body
(每次)把它放在你的口袋里
useEffect
用你的fetchData()
呼叫