我在使用Victory-Native库创建图表时遇到问题(click here要访问它的文档)
我正在尝试创建一个动态图表 . 我在状态中存储它的数据,并且如果按下“获取数据”按钮则想要修改 . 但是,我遇到了一个问题,经过5个小时的尝试,我无法解决自己 .
我还是React的新手,并试图弄清楚发生了什么,所以代码可能看起来像完全的胡言乱语 .
图表不是重新渲染线,而是渲染线但是杀死了我的Y轴域 .
这是具有正确域的图表,因为它应该看起来(当您向其提供静态数据时):
Note: 此时,data [5]仍然为空且未显示
按下蓝色的“GET DATA”按钮后,它会请求返回的值并将其放入数据[5] . 但是,这会完全杀死Y轴而不是重新渲染线 . 我究竟做错了什么?我希望该行只是继续正常使用我在代码中设置的域 .
This is what happens and shouldn't happen:
How can I make the chart render new value correctly?
码:
import React, {Component} from 'react';
import {AppRegistry, View, Button, Text} from 'react-native';
import { VictoryChart, VictoryLine, VictoryTheme } from "victory-native";
class testChart extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{data: 0, times: 0},
{data: 42, times: 1},
{data: 11, times: 2},
{data: 54, times: 3},
{data: 22, times: 4},
{data: null, times: null}
]
};
}
getDataBtn = () => {
const that = this;
fetch('http://192.168.1.111/getData').then(function(response){
let dataRsp = JSON.stringify(response.text());
let strData = dataRsp.substring(dataRsp.indexOf('Data:'), dataRsp.indexOf('.'));
var numData = strData.replace( /^\D+/g, ''); // ekstrakcija stevilk iz stringa
that.state.data[5].data = numData;
that.state.data[5].times = 5;
that.setState({data: that.state.data});
that.setState({text: JSON.stringify(that.state.data)});
});
}
render() {
return(
<View>
<Button color='blue' title='Get Data' onPress={() => this.getDataBtn()} />
<Text>Current DATA object value: {JSON.stringify(this.state.data)}</Text>
<VictoryChart theme={VictoryTheme.material} domain={{x: [0, 10], y: [0, 100]}}>
<VictoryLine
data={this.state.data}
x='times'
y='data'
/>
</VictoryChart>
</View>
);
}
}
AppRegistry.registerComponent('test', () => testChart);
2 回答
我认为这可能是因为
numData
是string
而不是int
. 请尝试执行以下操作您不应该以任何其他方式访问状态或修改它,如下所示:
如果你想存储这些数据而不是状态,并希望在所有类函数中都可以访问,那么你应该使用像
this.data = 5
等私有变量 .另一方面,在同一范围内调用setState将在React抛出的特定错误中失败,声明
there is a ongoing state change, you can't change it.
等 .您可以使用
this.setState({data: [], text: ''})
种方法,也可以在第一个setState函数的回调中设置状态 .希望有所帮助!