如何在FlatList中接收AsyncStorage项?

时间:2018-05-09 00:37:27

标签: reactjs react-native

我想要做的是在FlatList中显示保存在AsyncStorage中的项目。

import random
import time
import winsound
import sys
import os
import textwrap
import random


class pet:
    def __init__(self):
        self.petName = ''
        self.hungerLevel = 10
        self.happinesLevel = 10
        self.sleepy = False
        self.sadnessLevel = 0
        self.dead = False
        self.entratainiment_level = 15

myPet = pet()

global playedTimes
playedTimes = 0

def titleScreenOptions():
    playerOptions = input("> ")

    if playerOptions.lower() == "play":
        setupGame()

    elif playerOptions.lower() == "help":
        helpMenu()

    elif playerOptions.lower() == "quit":
        sys.exit()

    while playerOptions.lower() not in ["play", "help", "quit"]:
        print('sorry, your command was not recognized by my system, check for any speeling mistakes and try again.')
        print('You can type "help" at any give moment to see a list of basic commands')
        playerOptions = input("> ")

    if playerOptions.lower() == "play":
        setupGame()

    elif playerOptions.lower() == "help":
        helpMenu()

    elif playerOptions.lower() == "quit" or playerOptions.lower() == "exit":
        sys.exit()


def titleScreen():
    os.system('cls')
    print("#=====================================================================#")
    print("# Welcome to pymagochi, the game where you raise your own virtual pet #")
    print("#=====================================================================#")
    print("#                              |>PLAY<|                               #")
    print("#                              |>HELP<|                               #")
    print("#                              |>EXIT<|                               #")
    print("#=====================================================================#")
    print("#            |created by: julio|      |2018, Brazil|                  #")
    print("")
    titleScreenOptions()

def helpMenu():
    os.system('cls')
    print("#=============================================#")
    print("# type the commands in order to execute then, #")
    print("# here are some of the basic commands for you #")
    print("#                 >check<                     #")
    print("#                 >feed<                      #")
    print("#               >go to bed<                   #")
    print("#              >play a game<                  #")
    print("#=============================================#")
    print("# the rest you can figure it out by your self #")
    print("# I mean, you are not that stupid, are you?   #")
    print("#=============================================#")
    print("")
    titleScreenOptions()


def promptUser():
    print("#############################")
    print("what would you like to do?")
    userCommands = input(">> ")
    validCommands = ['feed', 'play a game', 'walk', 'eat', 'drink', 'go to bed', 'help me', 'quit', 'exit', 'clear', 'play', 'fun', 'check', 'status', 'help', 'sleep', 'rest']
    while userCommands.lower() not in validCommands:
        print('sorry, your command was not recognized by my system, check for any speeling mistakes and try again.')
        print('You can type "help" at any give moment to see a list of basic commands')
        userCommands = input(">> ")

    if userCommands.lower() == 'quit' or userCommands.lower() == 'exit':
        sys.exit()

    if userCommands.lower() == 'clear':
        clearScreen()

    elif userCommands.lower() in ['eat', 'feed', 'drink']:  
        feedPet()

    elif userCommands.lower() in ['play a game', 'play', 'fun']:
        playWithPet()

    elif userCommands.lower() in ['check', 'status']:
        checkStatus()

    elif userCommands.lower() in ['go to bed', 'sleep', 'rest']:
        sleepPet()

    elif userCommands.lower() in ['help me', 'help']:
        print("===========================================")
        print("type the commands in order to execute then,")
        print("here are some of the basic commands for you")
        print("                >check<                    ")
        print("                >feed<                     ")
        print("              >go to bed<                  ")
        print("             >play a game<                 ")
        print("===========================================")
        print("the rest you can figure it out by your self")
        print("I mean, you are not that stupid, are you?  ")
        print("===========================================")
        userCommands = input(">> ")


def feedPet():
    myPet.hungerLevel += 1
    if myPet.hungerLevel > 20:
        myPet.hungerLevel = 20
        print("thanks, but I am full already")

    print("thanks for feeding me!!!")
    promptUser()

def playWithPet():
    if myPet.sleepy == False:   
        print("yeah!!! let's play a game")
        myPet.hungerLevel -= 1
        myPet.entratainiment_level += 2
        gameChoice()
        if myPet.entratainiment_level >= 20:
            myPet.entratainiment_level = 20
    elif myPet.sleepy == True:
        print("I don't want to play now, I am tired :(")

    promptUser()



def gameChoice():
    print("what game do you want to play? A math game or blank")
    game_choice = input(">> ") 
    if game_choice == 'math game':
        for i in range(8):
            number1 = random.randint(1, 30)
            number2 = random.randint(1, 30)
            answer = (number1 + number2)    
            print("%d + %d = ?" %(number1, number2))
            player_answer = int(input(">> "))
            if player_answer == answer:
                print("congrats, you got it right")

            elif answer != player_answer:
                print("sorry, thats the wrong answer")
                break


def manageSleep():
    global playedTimes
    playedTimes += 1
    if playedTimes >= 5:
        playedTimes = 5
        print("I am tired, put me in bed please")

        myPet.sleepy = True


def checkStatus():
    print("name: %s " %myPet.petName)
    print("hunger: %d " %myPet.hungerLevel)
    print("happines: %d " %myPet.happinesLevel)
    print("sadnes: %d " %myPet.sadnessLevel)
    print("entratainiment level: %d " %myPet.entratainiment_level)
    print("is he tired: %s " %myPet.sleepy)
    print("is he dead: %s " %myPet.dead)
    promptUser()

def sleepPet():
    print("z")
    time.sleep(0.3)
    print("zZ")
    time.sleep(0.3)
    print("zZz")
    time.sleep(0.3)
    print("zZzZ")
    time.sleep(0.3)
    print("zZzZz")
    time.sleep(0.3)
    print("zZzZzZ")
    time.sleep(0.3)
    print("zZzZzZz")
    myPet.sleepy = False
    print("Good morning, I feel better already")
    promptUser()



def clearScreen():
    os.system("cls")
    promptUser()

def setupGame():
    print("hello, welcome to pymagochi, where you are going to raise your own virtual pet")
    print("what would you like to name it?")
    name = input(">>")
    myPet.petName = name
    print("%s is a great name for a pet" %myPet.petName)
    time.sleep(3)
    os.system("cls")
    promptUser()


titleScreen()
titleScreenOptions() 

1 个答案:

答案 0 :(得分:0)

您可以使用状态并在componentDidMount中初始化它:

state = {
  data: [],
}

componentDidMount() {
  AsyncStorage.getItem('posts').then(data => this.setState({ data }));
}

<FlatList data={this.state.data} ...otherProps />

或者,如果您使用Redux,则可以在任何地方调用AsyncStorage.getItem并发送操作以填充商店,FlatList组件可以连接到该商店并显示数据。

相关问题