React native 如何在react native中重新启动当前屏幕?

React native 如何在react native中重新启动当前屏幕?,react-native,React Native,我正在做一些图表工作,当我改变图表时 而不是试图寻找屏幕中的所有变量为零,并查看所有图形函数以使其处于活动状态 我只想重新启动当前屏幕,这意味着它将第一次进入同一场景 我如何在不实际退出和重新进入场景的情况下做到这一点 这是我的代码: import React, {Component} from 'react'; import {View, Text, StyleSheet, processColor, Picker} from 'react-native'; import { Button}

我正在做一些图表工作,当我改变图表时 而不是试图寻找屏幕中的所有变量为零,并查看所有图形函数以使其处于活动状态 我只想重新启动当前屏幕,这意味着它将第一次进入同一场景

我如何在不实际退出和重新进入场景的情况下做到这一点

这是我的代码:

import React, {Component} from 'react';
import {View, Text, StyleSheet, processColor, Picker} from 'react-native';
import { Button} from "native-base";
import './globals.js'


import {CombinedChart} from 'react-native-charts-wrapper';
import moment from 'moment';

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'stretch',
        backgroundColor: 'transparent',
        paddingTop:20
    }
});

var InsulinShort = [];
var InsulinLong = [];
var glocuseTests = [];
const injectionsCount = 1000;

for (var i = 1; i < injectionsCount; i++) {
    var random = Math.random();
    if (random <= 0.7) {
        var gloguseValue = Math.floor(Math.random() * 40) + 75;
        var gloguseposition = Math.random();

        glocuseTests.push({x:i+gloguseposition, y: gloguseValue, marker: "level: "+gloguseValue});

    }
}
for (var i = 1; i < injectionsCount; i++) {
    var random = Math.random();
    if (random <= 0.15) {
        var shortvalue = Math.floor(Math.random() * 16) + 1  ;
        var shortPosition = Math.round(Math.random() * 100) / 100;
        InsulinShort.push({x:i+shortPosition,y: shortvalue*20, marker: shortvalue+ " units of short insulin"});
    }else if (random <= 0.3) {
        var longePosition = Math.round(Math.random() * 10) / 10;
        var longvalue = Math.floor(Math.random() * 16) + 1;
        InsulinLong.push({x:i+longePosition,y: longvalue*20, marker: longvalue+ " units of long insulin"});
    }else{
    }
}
export default class LogGraph extends Component {

    constructor() {
        super();
        // var valueFormatter = new Array(3515599953920);


        this.state = {
            selectedPeriod: "all",
            loading: true,
            days:365,
            legend: {
                enabled: true,
                textSize: 18,
                form: 'SQUARE',
                formSize: 18,
                xEntrySpace: 10,
                yEntrySpace: 5,
                formToTextSpace: 5,
                wordWrapEnabled: true,
                maxSizePercent: 0.5
            },
            xAxis: {
                valueFormatter: [
                    '01/04/18',
                    '02/04/18',
                    '03/04/18',
                    '04/04/18',
                    '05/04/18',
                    '06/04/18',
                    '07/04/18',
                    '08/04/18',
                    '09/04/18',
                    '10/04/18',
                    '11/04/18',
                    '12/04/18',
                    '13/04/18',
                    '14/04/18',
                    '15/04/18',
                    '16/04/18',
                    '17/04/18',
                    '18/04/18',
                    '19/04/18',
                    '20/04/18',
                ],
                // valueFormatterPattern:'ssss',
                // limitLines:100,
                // drawLimitLinesBehindData:false,
                // avoidFirstLastClipping: false,
                textColor: processColor('#000'),
                gridColor: processColor('#000'),
                axisLineColor: processColor('#000'),
                drawGridLines:true,
                drawAxisLine:false,
                drawLabels:true,

                granularityEnabled: true,
                // granularity:1515599953920,
                granularity: 1,
                // granularity: 131096  ,
                position:'TOP',
                textSize: 10,
                labelRotationAngle:45,
                gridLineWidth: 1,
                axisLineWidth: 2,
                gridDashedLine: {
                    lineLength: 10,
                    spaceLength: 10
                },
                centerAxisLabels:false,
            },

            yAxis: {
                left: {
                    axisMinimum: 0,
                    axisMaximum: 400,
                    labelCount: 6,
                    labelCountForce: true,
                    granularityEnabled: true,
                    granularity: 5,
                },
                right: {
                    axisMinimum: 0,
                    axisMaximum: 20,
                    labelCount: 6, // 0 5 10 15 20 25 30
                    labelCountForce: true,
                    granularityEnabled: true,
                    granularity: 5,
                }
            },

            marker: {
                enabled: true,
                markerColor: processColor('#F0C0FF8C'),
                textColor: processColor('white'),
                markerFontSize: 18,
            },

            data: {
                barData: {
                    config: {
                        barWidth: 1 / 24 ,
                    },
                    dataSets: [{
                        values:InsulinLong,
                        label: 'Long Insulin',
                        config: {
                            drawValues: false,
                            colors: [processColor('#a2a4b2')],
                        }
                    },{
                        values:InsulinShort,
                        label: 'Short Insulin',
                        config: {
                            barShadowColor: processColor('red'),
                            highlightAlpha: 200,
                            drawValues: false,
                            colors: [processColor('#d0d5de')],
                        }
                    }]

                },
                lineData: {
                    dataSets: [{
                        values: glocuseTests,
                        label: 'Glucose Level',
                        config: {
                            drawValues: false,
                            colors: [processColor('#0090ff')],
                            // mode: "CUBIC_BEZIER",
                            drawCircles: true,
                            lineWidth: 3,
                        }
                    }],
                },
            }
        };

    }


    pickerZoomSelected (value) {
      // this.setState({selectedPeriod: value})
      global.graphStateChoosen = value
      this.resetscreen();

    }

    resetscreen() {

    }


    pickerDaysSelected (value) {
      this.setState({days: value})
    }

    isGraphItemLegal (itemTime) {

      // console.log ("log was made at: "+itemTime)

      // multiplied by 1000 so that the argument is in milliseconds, not seconds.
      var itemDate = new Date(itemTime*1000);
      // Hours part from the timestamp
      var itemHour = itemDate.getHours();
      // Minutes part from the timestamp
      var itemMinutes = "0" + itemDate.getMinutes();
      // Seconds part from the timestamp
      var itemSeconds = "0" + itemDate.getSeconds();

      // console.log ("refactured: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
      // console.log ("selected piriod: " + this.state.selectedPeriod);

      if (global.graphStateChoosen == "all")  {
        // console.log ("dont show item+1");
        return true;
      }

      // //blocks morning \ afternoon \ evening
      if ((itemHour > 18) && (itemHour < 24)) {
        console.log ("EVENING ITEM: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
        // console.log ("is it equal ?: " + this.state.selectedPeriod == "evening");

        if (!(global.graphStateChoosen == "evening")|| (global.graphStateChoosen == "all"))  {
          // console.log ("dont show item+1");
          return false;
        }

      } else if ((itemHour > 6) && (itemHour < 13)) {
        console.log ("MORNING ITEM: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
        // console.log ("is it equal ?: " + this.state.selectedPeriod == "evening");
        if (!(global.graphStateChoosen === "morning")|| (global.graphStateChoosen == "all"))  {
          // console.log ("dont show item+2");
          return false;
        }

      } else if ((itemHour > 13) && (itemHour < 18)) {
        console.log ("AFTERNOON ITEM: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
        if (! (global.graphStateChoosen == "afternoon") || (global.graphStateChoosen == "all"))  {
          // console.log ("dont show item+3");
          return false;
        }
      }

      return true;

    }

    clearList() {

    }

    creatList(logs){
        // var startTime = moment().millisecond();

        var list = [];

        var time = false;

        if (logs) {
            // console.log('firstLogDay',moment(firstLogDay).format('L'));
            let gloguseItems   = [];
            let shortItems     = [];
            let longItems      = [];
            let firstValidFlag = false;
            let firstLogTime;
            let lastLogTime;
            let days;
            let firstLogDate;
            let firstLogDayTime;
            lastLogTime        = logs[0].time;
            for (var i = logs.length-1; i >= 0; i--) {
                console.log ("cheking i: "+i);
                let item = logs[i];
                if ( !firstValidFlag &&  ['glucose', 'long', 'short'].indexOf(item.type) >= 0 )  {
                    // debugger;
                    firstValidFlag = true;
                    firstLogTime = logs[i].time;
                    days = Math.round((lastLogTime-firstLogTime)/(1000*60*60*24));
                    firstLogDate = moment(firstLogTime).format('YYYY-MM-DD');
                    // console.log('firstLogDate',firstLogDate);
                    firstLogDayTime = new Date(firstLogDate);
                    firstLogDayTime = firstLogDayTime.getTime() - (2*60*60*1000);
                    // console.log('firstLogDayTime',firstLogDayTime);
                }

                console.log ("runing on i: "+i);
                console.log ("with our time: "+this.state.graphStateChoosen);

                var isItemLegal = this.isGraphItemLegal(item.time);

                console.log ("answer is: " + isItemLegal);

                if ((firstValidFlag) && (isItemLegal)) {

                    let logX = ( item.time - firstLogDayTime ) /  1000 / 60 / 60 /24;

                    // logX =  Math.round(logX * 10) / 10
                    if (logX) {
                        // logX = item.time;
                        // console.log(logX);
                        let logY = item.amount;
                        if (item.type !== 'glucose') {
                            if (item.type === 'short') {
                                shortItems.push({
                                    x: logX,
                                    y:  logY*20,
                                    marker: logY+ " units of short insulin" + moment(item.time).format('LLL')
                                })
                            }
                            if (item.type === 'long') {
                                longItems.push({
                                    x: logX,
                                    y:  logY*20,
                                    marker: logY+ " units of long insulin" +  moment(item.time).format('LLL')
                                })
                            }
                        }else{
                            if(item.type === 'glucose'){
                                gloguseItems.push({
                                    x: logX,
                                    y: parseInt(logY),
                                    marker: "level: "+ logY +  moment(item.time).format('LLL')
                                })
                            }
                        }
                    }
                }

            }

            console.log ("Reached Here");

            let oldData = this.state.data;

            console.log ("Reached Here 1");
            oldData.lineData.dataSets[0].values = gloguseItems;
            oldData.barData.dataSets[1].values = shortItems;
            oldData.barData.dataSets[0].values = longItems;


            let DayFlag = firstLogDate;
            let valueFormatter = [];

            console.log ("Reached Here 2");
            valueFormatter.push(moment(DayFlag).format('DD/MM/YYYY'));
            for (let i = 0; i < days; i++) {
                DayFlag = moment(DayFlag).add(1, 'days');
                valueFormatter.push(DayFlag.format('DD/MM/YYYY'));
            }

            console.log ("Reached Here 3");
            let xAxis = this.state.xAxis;
            xAxis.valueFormatter = valueFormatter;
            console.log ("Reached Here 4");
            this.setState({
                data:oldData,
                days:days,
                xAxis:xAxis,
                loading:false
            });

            console.log ("Reached Here 5");

        }else{
            this.setState({loading:false});
        }

    }

    componentDidMount() {

        this.creatList(this.props.logs);
    }

    zoomTwentyPressed() {
      console.log ("pressed 25");
    }

    zoomFiftyPressed() {
      console.log ("pressed 50");
    }

    zoomHundredPressed() {
      console.log ("pressed 100"+this.state.days);
      // CHANGE ZOOM HERE
      // this.combinedChart.zoom = 80
      // this.setState({days: this.state.days/2})

    }


    static displayName = 'Combined';

    handleSelect(event) {
        let entry = event.nativeEvent
        if (entry == null) {
            this.setState({...this.state, selectedEntry: null})
        } else {
            this.setState({...this.state, selectedEntry: JSON.stringify(entry)})
        }

        // console.log(event.nativeEvent)
    }

    render() {
        return (

            <View style={styles.container}>

                {
                    (this.state.loading) ? <Text>Loading</Text>:
                    <CombinedChart
                        data={this.state.data}
                        ref={component => this.combinedChart = component}
                        xAxis={this.state.xAxis}
                        yAxis={this.state.yAxis}
                        legend={this.state.legend}
                        onSelect={this.handleSelect.bind(this)}
                        onChange={(event) => console.log(event.nativeEvent)}
                        marker={this.state.marker}
                        animation={{durationY: 1000,durationX: 1000}}
                        maxVisibleValueCount={16}
                        autoScaleMinMaxEnabled={true}
                        zoom={{scaleX: Math.floor(this.state.days/12), scaleY: 1, xValue:  4, yValue: 4, axisDependency: 'LEFT'}}
                        style={styles.container}/>
                }

                <Text style={{
                  paddingLeft: 20,
                  fontSize: 20
                }}>
                  Zoom Options
                </Text>

                <View style={styles.buttonWrap}>

                    <View style={{
                      flexDirection:'row',
                      marginLeft:20,
                      paddingLeft: 80,
                      paddingTop: 20,
                      justifyContent: 'space-around',
                    }}>


                    <Picker
                      style={{width:'80%'}}
                      selectedValue={this.state.PickerValueLong}
                      onValueChange={ (itemValue, itemIndex) => {
                          // console.log(this);
                          this.pickerDaysSelected(itemValue);
                        }}>

                      <Picker.Item label="x100 Days" value='100' />
                      <Picker.Item label="x50 Days" value='50' />
                      <Picker.Item label="x25 Days" value='25' />

                    </Picker>


                    <Picker
                      style={{width:'80%'}}
                      selectedValue= {global.graphStateChoosen}
                      onValueChange= {(itemValue, itemIndex) => {
                          // console.log(this);
                          this.pickerZoomSelected(itemValue);
                        }}>

                      <Picker.Item label="Morning" value='morning' />
                      <Picker.Item label="Afternoon" value='afternoon' />
                      <Picker.Item label="Evening" value='evening' />
                      <Picker.Item label="All Day" value='all' />

                    </Picker>




                    </View>



                </View>

            </View>


        );

    }
}

thnx

称之为此。组件将挂载

您通常不会在该屏幕内执行此操作。但在它的容器上,可以渲染空值,然后再次渲染场景

请在你的答案中添加更多细节。为什么这样做有效?你解决的问题是什么?这使OP和未来的每个人都更容易理解他们的问题。这无助于它不会重新启动场景,只需进入组件即可再次装载。。所有内存功能和veriables将保持不变,就像屏幕已经存在一样。而不是第一次启动它,你会从场景按钮监听器调用什么函数?我更愿意从它的容器中注入一个回调,在容器级别上改变它。比如说。。。将其容器上的isVisible状态设置为false并返回true。只有当它是真的时才渲染。。。。因此,它将摧毁并重新建造。现在,请理解我们从一开始就在谈论黑客。对我来说,最好的方法是使用重置函数来清除混乱,而不是试图破坏/构建视图。您可以创建一个初始化方法,在构造函数上调用它,然后在需要重置时再次调用。据我所知,在React中,视图和状态是两个非常独立的概念,您必须了解这一点,并尽最大努力做到这一点,以便能够构建更好的应用程序。