首页 > 解决方案 > React Native 状态不会改变

问题描述

我正在开发我的第一个游戏应用程序。

我想要做的是将 GreenF 传递给 Green 组件。

但是状态不会改变。我需要在函数 play() 中随时更改 GreenF;

这只是我的代码的开始,所以没有什么是完整的,只是为了你的理解。

    import React, {Component} from 'react';
    import {StyleSheet, Text, View,TouchableOpacity, Button} from 'react-native';
    import Green from './components/Green.js'

     constructor (props){
    super(props);
    this.state = {
      greenF: false,
      score: 0,
      seq: [1,2,3,1,4],
      playerSeq: [],
      round: 1,
    }
  }

  play() {
    this.setState({ greenF: true });
  }

  render(){
    return (
      <View>
        <Button 
        title='start' 
        color='black' 
        onPress={this.play}>

        </Button>
        <Green greenFlash={this.state.greenF}> </Green>
      </View>
    );
  }
}

标签: javascriptreactjsreact-nativeenvironment-variables

解决方案


您可以使用AsyncStoragereact-native-community 提供的。它是一个持久存储,您可以在其中设置和获取键值存储。参考这个:https ://github.com/react-native-community/async-storage

无论哪种方式,您都可以使用 redux 进行全局状态管理。


推荐阅读