问题描述
在另一个具有更新状态的组件中选择图表的符号,该状态会作为道具传递回此TradingView组件。
我正在尝试通过以下方式更改图表中的符号:
this.tvWidget.chart().setSymbol('BINANCE:' + this.props.selectedSymbol.name)
但是我应该在哪里以及如何确切地放置和使用它?我很困惑。
我需要更改图表符号,但是应该以什么方法进行更改? 谢谢!
import * as React from 'react';
import './index.css';
import {widget} from '../../charting_library/charting_library.min';
import {setSymbol} from "../../store/actions/symbols";
import {connect} from "react-redux";
class TradingView extends React.PureComponent {
tvWidget = null;
widgetoptions = {
client_id: 'Tradingview.com',user_id: 'public_user_id',datafeed: new window.datafeeds.UDFCompatibledatafeed('https://demo_Feed.Tradingview.com'),charts_storage_url: 'https://saveload.Tradingview.com',symbol: "AAPL",symbol: this.props.selectedSymbol ? this.props.selectedSymbol.name : "BTCUSDT",snapshot_url: "https://www.Tradingview.com/snapshot/",enabled_features: ['study_templates'],studies: ["RSI@tv-basicstudies","stochasticRSI@tv-basicstudies","MACD@tv-basicstudies"],watchlist: ["BINANCE:BTCUSDT"],disabled_features: ['use_localstorage_for_settings'],library_path: '/charting_library/',charts_storage_api_version: '1.1',container_id: 'tv_chart_container',debug: false,interval: 'D',theme: "Dark",allow_symbol_change: true,auto_save_delay: '5',range: "6m",hide_legend: true,locale: "en",timezone: "Europe/Berlin",autosize: true,enable_publishing: true,};
componentDidMount() {
this.tvWidget = new widget(this.widgetoptions);
let tvWidget = this.tvWidget
tvWidget.onChartReady(() => {
tvWidget.headerReady().then(() => {
let chart = tvWidget.chart();
chart.onSymbolChanged().subscribe(null,onChartSymbolChanged);
})
})
let setSymbol = this.props.setSymbol
let symbols = this.props.symbols
function onChartSymbolChanged() {
let chart = tvWidget.chart();
console.log("onChartSymbolChanged changing symbol to " + chart.symbol());
setSymbol(symbol)
}
}
componentwillUnmount() {
if (this.tvWidget !== null) {
this.tvWidget.remove();
this.tvWidget = null;
}
}
render() {
this.tvWidget && this.tvWidget.symbol ? this.tvWidget.chart().setSymbol('BINANCE:' + this.props.selectedSymbol.name) : null
return (
<div
id="tv_chart_container"
className={'TVChartContainer'}
/>
);
}
}
const mapStatetoProps = state => {
return {
symbols: state.symbols.symbols,selectedSymbol: state.symbols.selectedSymbol
};
};
const mapdispatchToProps = {setSymbol}
export default connect(mapStatetoProps,mapdispatchToProps)(TradingView);
解决方法
您可以通过在componentDidUpdate(prevProps) {}
中传递prevPops来检查道具并检查更改。
我通过在货币对发生变化时删除图表来使其工作。我不知道这是不是最优化的方式。
function TradingView(props) {
const { pair } = props;
const tv = useRef(null);
useEffect(() => {
if (tv.current) tv.current.remove();
tv.current = new window.TradingView.widget({ symbol: pair });
},[pair]);
return <div id="trading_view_chart" />;
}