我正在使用 recharts
,如果 data
变量在类之外,它工作正常。发生的事情是它加载、动画图形并显示“点”坐标。但是,如果 data
变量在类内部,则它不会设置动画,也不会更新“点”坐标 css。
请注意 render 方法中注释掉的数据,如果我取消注释并注释掉顶部数据变量,它不起作用,但当前设置工作正常。任何修复的想法?修复后,我最终想加载 this.props.data
而不是 data
。
const data = [{ name: '07/14/2017', mood: 6 }, { name: '07/15/2018', mood: 7 }];
class LinearGraph extends Component {
constructor(props) {
super(props);
}
render() {
//const data = [{ name: '07/14/2017', mood: 6 }, { name: '07/15/2018', mood: 7 }];
return (
<ResponsiveContainer width="100%" height="80%">
<LineChart
data={data}
margin={{ top: 5, right: 50, left: 0, bottom: 5 }}
>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid
strokeDasharray="3 3"
horizontal={false}
/>
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey="mood"
stroke="rgba(43, 191, 217, 0.9)"
dot={{ stroke: '#ff0000', strokeWidth: 12 }} // this isn't working at all
activeDot={{ r: 1 }}
strokeWidth={5}
/>
<ReferenceLine y={7} label="Max" stroke="green" strokeDasharray="3 3" />
</LineChart>
</ResponsiveContainer>
);
}
}
同样为了更直观的理解,在这张照片中它是工作的时候(无法显示动画,但你可以看到“点”坐标正在工作):
编辑:我也尝试在 componentWillMount 中设置状态(和 componentDidMount 但后者给出了警告):
class LinearGraph extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentWillMount() {
this.setState({ data: this.props.data });
}
render() {
return (
<ResponsiveContainer width="100%" height="80%">
<LineChart data={this.state.data} />
</ResponsiveContainer>
);
}
}
最佳答案
render
在状态改变时被调用。你需要复习 react component's lifecycle .最佳做法是声明您的状态,然后将其加载到生命周期 componentDidMount
函数中。
class LinearGraph extends React.Component {
constructor(props) {
super(props);
this.state = {
data = []
};
}
componentDidMount() {
// Get your data here, from a const or an API
fetch('api/get_data')
.then(res => res.json()) // Get the json
.then(res => this.setState({data: res.data})) // Consume the json
.catch(err => alert('foo'));
}
render() {
return (
<div>
<LineChart data={this.state.data} />
</div>
);
}
}
关于javascript - 完全被这个 reactjs 逻辑难住了,变量不更新组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45200725/