很抱歉我是个反应新手。我尝试使用重图表库绘制图表。
首先,我使用API从服务器获取数据,并将其作为支持传递给子组件。如果我在render()中直接使用this.props.selectablefields,那么它就能正常工作。但在单击图例标签时,我必须实现一些功能。
因此,我根据这些数据设置状态,并在render()中使用该状态。但是这个状态在第一时间是空的(第一次加载)。如果我在没有任何修复的情况下重新保存代码,那么这就是工作。(不刷新.)这是我的密码。
export default class AnalysLineChart extends Component {
constructor(props){
super(props);
this.selectBar = this.selectBar.bind(this);
this.state = {
labels: this.props.selectablefields
}
}
selectBar(event) {
//do something......
}
render() {
return (
<LineChart width={300} height={250} data={this.props.data}>
<XAxis dataKey="date"/>
<YAxis/>
<Legend onClick={this.selectBar} />
{
//this code is work well but can't implement legend click functions
//this.props.selectablefields.map((label, index)) => (
this.state.labels.map((label, index) => (
<Line key={index} type="monotone" dataKey={label.key} stroke={label.color} />
))
}
</LineChart>
);
}
}有谁可以帮我?
注意:当我点击图例标签时,它会根据点击的图例显示并隐藏图表。
selectBar函数是这样的(但这在这个问题上并不重要)
selectBar(event) {
let updatedLabels = [];
for (let i = 0; i < this.state.labels.length; i++) {
let label = this.state.labels[i];
if (label.key != event.dataKey) {
updatedLabels.push(label);
} else {
if (/\s/.test(label.key)) {
let newLabel = { key: label.key.trim(), color: label.color };
updatedLabels.push(newLabel);
}
else {
let newLabel = { key: label.key + " ", color: label.color };
updatedLabels.push(newLabel);
}
}
}
this.setState({
labels: updatedLabels
});
}图表看上去像这样。

这是在单击CPA图例后隐藏CPA图形时的图片。

发布于 2020-11-30 06:22:04
最后,我解决了这个问题。这可能是因为setState函数是异步操作的。我这样修正了我的代码,并且运行得很好。
export default class AnalysLineChart extends Component {
constructor(props){
super(props);
this.selectBar = this.selectBar.bind(this);
this.state = {
labels: []
}
}
selectBar(event) {
//do something......
}
componentDidMount(){
this.setState({
labels: this.props.selectablefields
});
}
render() {
return (
<LineChart width={300} height={250} data={this.props.data}>
<XAxis dataKey="date"/>
<YAxis/>
<Legend onClick={this.selectBar} />
{
this.state.labels.map((label, index) => (
<Line key={index} type="monotone" dataKey={label.key} stroke={label.color} />
))
}
</LineChart>
);
}
}发布于 2020-11-26 01:07:56
我认为你描述得不够清楚。
通常,你所做的就是你所做的,这就是映射this.props.selectablefields,因为将这个支柱保存到状态似乎是一种过度杀戮……
当点击“联想”组件时,您到底想实现什么?
https://stackoverflow.com/questions/65014512
复制相似问题