导航后如何保持以前的状态

时间:2018-08-31 17:57:02

标签: react-native state

//Home page

class Home extends Component {
    constructor(props){
      super(props);
      this.state = {time: ""}
    }

    render(){
      const { navigate } = this.props.navigation;
      return(
        <View>
          <TextInput onChangeText={(time) => this.setState({ time })} placeholder = "enter time" />
          <TouchableOpacity style={{marginTop: 10, height: 20, width: 50, borderRadius: 6, borderColor: 'white', backgroundColor:'red'}}
            onPress = { () => {
                navigate('Wait', {
                  time: this.state.time * 1000
                })
            }}
            >
            <Text style={{color: 'white'}}>add</Text>
          </TouchableOpacity>
        </View>
      )
    }
}


//Waitlist page

class Wait extends Component{
  constructor(props){
    super(props);
    this.state = { data: []}
  }

  renderTime(){
    return this.state.data.map((item) => {
      return(
        <View>
          <TimerCountdown
           initialSecondsRemaining={ item }
           allowFontScaling={true}
           style={{ fontSize: 20 }}
          />
        </View>
      )
    })
  }

  updatestate(time){
    var temp = this.state.data
    temp.push(time)
    this.setState({data: temp})
  }

  render(){
    const { navigate } = this.props.navigation;
    const { navigation } = this.props;
    const time = navigation.getParam('time', 'NO-Name');

    return(
      <View>
          <TouchableOpacity onPress = {()=>{ this.updatestate(time)}}>
              <Text> Update </Text>
          </TouchableOpacity>
          <View>
            {this.renderTime()}
          </View>
      </View>
    )
  }
}

我正在尝试编写一个函数,以继续向其他页面添加倒数计时器。用户输入输入时间后,它应导航到等待列表页面并更新状态并呈现所有计时器。上面的代码不起作用,因为每次我导航到该页面时,状态都会重置。

我也在AsyncStorage上尝试过。我能够在主页上的AsyncStorage中添加时间,并在等待列表页面上进行渲染。但是问题在于,每次添加新计时器时,所有计时器都会重置。

我只想知道导航到另一个页面后如何保持以前的状态。有人可以告诉我一些例子吗?非常感谢。

计时器倒计时的文档:https://www.npmjs.com/package/react-native-timer-countdown

0 个答案:

没有答案
相关问题