单击按钮刷新图表

Refresh Graph on button click

我正在尝试在我的应用程序中创建一个按钮,该按钮将使用 React Native 按钮组件刷新图表中的随机数据(使用 react-native-chart-kit 制作)。我的代码如下:

import * as React from 'react';
import {useState} from 'react';
import { StyleSheet, Text, View, Switch, Dimensions, Button, Alert } from 'react-native';
import { LineChart } from "react-native-chart-kit";
import Header from "./components/Header";
import Colors from "./constants/colors";


export default function App() {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  function refresh_data(){
    ...
    //Code here?
    ...
  }

  return (
    <View style = {styles.screen}>
      <View style = {styles.button}>
        <Button
          title="Refresh"
          color={Colors.primary}
          onPress={() => refresh_data}
        />
      </View>

      <View style = {styles.graph}>
        <View style = {{flex: 1}}>
          <Text style = {styles.text}>Bezier Line Chart</Text>
        </View>

        <View style={{flex: 2}}>
        <LineChart
          data={{
            labels: ["January", "February", "March", "April", "May", "June"],
            datasets: [{
              data: [
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100                
              ]
              }]
          }}
          width={Math.floor(Dimensions.get("window").width * 0.6)} // from react-native
          height={220}
          yAxisLabel="$"
          yAxisSuffix="k"
          yAxisInterval={1} // optional, defaults to 1
          chartConfig={{
            backgroundColor: "#e26a00",
            backgroundGradientFrom: "#fb8c00",
            backgroundGradientTo: "#ffa726",
            decimalPlaces: 2, // optional, defaults to 2dp
            color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
            labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
            style: {
              borderRadius: 16
            },
            propsForDots: {
              r: "6",
              strokeWidth: "2",
              stroke: "#ffa726"
            }
          }}
          bezier
          style={{
            marginVertical: 8,
            borderRadius: 16
          }}
        />
      </View>

    </View>

  </View>
  );
}

const styles = StyleSheet.create({
  screen: {
  flex: 1,
  alignItems: 'stretch',
  justifyContent: 'center'
  },
  button: {
  alignSelf: 'center',
  justifyContent: 'center',
  flex: 1
  },
  graph: {
  flex: 3,
  alignItems: 'center',
  justifyContent: 'center'
  }
});

我是 Javascript 和 React 的新手,所以这可能是一个非常基本的问题,我想了解更多。有人认为我尝试过使用 location.reload() 重新加载整个页面,但这不是我要找的(我知道因为它在应用程序的另一部分有一个开关,只要点击它就会刷新数据,我就是想不通)。在此先感谢您的帮助!

向组件状态添加一些初始 "random" 数据,并在 refresh_data 单击处理程序中使用新的 "random" 数据设置状态。

此外,设置 onClick回调的正确语法是onClick={refresh_data} onClick={() => refresh_data()} .

export default function App() {
  const [randomData, setRandomData] = useState([
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100,
    Math.random() * 100                
  ]);

  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  function refresh_data(){
    setRandomData([
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100,
      Math.random() * 100                
    ])
  }

  return (
    <View style = {styles.screen}>
      <View style = {styles.button}>
        <Button
          title="Refresh"
          color={Colors.primary}
          onPress={refresh_data}
        />
      </View>

      <View style = {styles.graph}>
        <View style = {{flex: 1}}>
          <Text style = {styles.text}>Bezier Line Chart</Text>
        </View>

        <View style={{flex: 2}}>
        <LineChart
          data={{
            labels: ["January", "February", "March", "April", "May", "June"],
            datasets: [{ data: randomData }]
          }}
          width={Math.floor(Dimensions.get("window").width * 0.6)} // from react-native
          height={220}
          yAxisLabel="$"
          yAxisSuffix="k"
          yAxisInterval={1} // optional, defaults to 1
          chartConfig={{
            backgroundColor: "#e26a00",
            backgroundGradientFrom: "#fb8c00",
            backgroundGradientTo: "#ffa726",
            decimalPlaces: 2, // optional, defaults to 2dp
            color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
            labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
            style: {
              borderRadius: 16
            },
            propsForDots: {
              r: "6",
              strokeWidth: "2",
              stroke: "#ffa726"
            }
          }}
          bezier
          style={{
            marginVertical: 8,
            borderRadius: 16
          }}
        />
      </View>

    </View>

  </View>
  );
}

虽然有很多重复,所以我还创建了一个随机数据实用程序:

const createRandomData = (length = 10) => Array(length)
  .fill()
  .map(() => Math.random() * 100);

const createRandomData = (length = 10) => Array(length).fill().map(() => Math.random() * 100);

console.log(createRandomData(3));
console.log(createRandomData(6));
console.log(createRandomData(12));

新用法:

const [randomData, setRandomData] = useState(createRandomData(12));
...
setRandomData(createRandomData(12));