【问题标题】:React Native How to Set StateReact Native 如何设置状态
【发布时间】:2020-04-29 02:15:32
【问题描述】:

我正在 EdX 上学习 CS50 移动应用程序课程并构建一个简单的刽子手应用程序以确保我理解这些概念。下面是我写的代码。我遇到的问题是该应用程序不会在每次猜测后更新显示屏上的“HiddenWord”。我相信这是因为我设置 class/setState 函数的方式存在错误,但是我似乎无法弄清楚如何正确地做到这一点。当用户开始一个新游戏时,游戏词被设置为古生物学(就像测试一样,最终它要么是多人游戏,要么是从一大堆词中随机选择的)。当一个字母被猜到时,游戏词的“警报”是空白的,所以我知道由于某种原因,按下新游戏时状态没有更新。

感谢任何帮助。

import React from 'react';
import {View, TouchableOpacity, Text, ScrollView, StyleSheet, Switch, TextInput, FlatList} from 'react-native'
import {Constants} from 'expo'


let wins = 0
let losses=0
let word=""
let wrongletters=[]
let lengthofword=0
let testcounter=0
let isright=true
let rightcount=0
let wrongcount=0
let youwon=false
let youlost=false
let gameWord=""
let hiddenWord=""

export default class Hangman extends React.Component {
  constructor() {
    super()

    this.state = {
      gameWord: "",
      hiddenWord: ""
    }
  }

  newGame() {
      this.setState ({
      gameWord: "paleontology",
      hiddenWord: "__________"
     })

   // const text = `TODO number ${id}`
  }


  checkletter(guess) {
    alert (gameWord)
    for(let i = 0; i < gameWord.length; i++){
      if (gameWord[i] === guess) {
           hiddenWord[i] = guess;
        rightcount=rightcount+1;

          }
      else {
        testcounter=testcounter+1;
        if(testcounter===gameWord.length){
            wrongletters= {wrongletters, guess};
              wrongcount=wrongcount+1;
        }
      }
     if(gameWord===hiddenWord){
    youwon=true;
    }
     if(wrongcount===6){
    youlost=true;

    }
this.setState({hiddenWord:hiddenWord})
  }

  }
  componentDidMount() {
    let that = this
    let items = ["A", "B", "C", "D", "E", "F", "G","H","I","J", "K", "L", "M", "N", "O", "P","Q", "R", "S", "T", "U","V","W","X", "Y", "Z"]
    that.setState({
      dataSource: items,
    });
  }
  render() {
    return (

      <View style={[styles.appContainer, styles.fill]}>
        <Text style={styles.title}>
        Hang With Friends-Single Player Mode</Text>

     <TouchableOpacity style={styles.buttonTemp} onPress={() => this.newGame()}>
        <Text style={styles.buttonText}>New Game</Text>
      </TouchableOpacity>
<Text> </Text>

    <FlatList style ={styles.letterGrid}
          data={this.state.dataSource}
          renderItem={({ item }) => (
             <TouchableOpacity style={styles.letterButtons} onPress={() => this.checkletter(item)}>
      <Text style={styles.buttonText}>{item}</Text>
      </TouchableOpacity>
          )}
          //Setting the number of column
          numColumns={13}

        />


<Text style={styles.wordtoGuess}>
    {hiddenWord}</Text>
     <Text>Wrong Guesses so Far: {wrongletters}</Text>
</View>

    );
  }
}



const styles = StyleSheet.create({
  wordtoGuess: {
    fontWeight: "bold",
    marginVertical: 25,
    color: "blue",
    fontSize: 25,
    textAlign: "center",
    textDecorationLine: "underline",
    letterSpacing: 10,
    textDecorationColor: "black",
  },
  appContainer: {
    paddingTop: 50,
    backgroundColor: "white",
  },
  title: {
    fontWeight: "bold",
    marginVertical: 59,
    color: "red",
    fontSize: 30,
    textAlign: "center",
    textShadowColor: "black",
    textShadowRadius: 2,
    fontFamily: ""
  },
  buttonTemp: {
   alignItems: "center",
    backgroundColor: "blue",
    marginHorizontal: 40,
    borderRadius:23,
    padding: 10
  },
  buttonText:{
    color: "white",
    fontWeight: "bold"
  },
  letterButtons: {
    alignItems: "center",
    backgroundColor: "red",
    marginHorizontal: 0,
    borderRadius:0,
    padding: 6
  },
  letterGrid:{
paddingTop: 10,
    backgroundColor: "white",
    alignItems:"center",
    marginHorizontal:20
  }


})


【问题讨论】:

  • 您好!你能提供一个snack.expo.io 的例子吗?调试起来更容易:)

标签: reactjs react-native class setstate


【解决方案1】:

您不必let that = this

that.setState({  //???
      dataSource: items,
    });

就这样使用吧。

this.setState({  //this 
      dataSource: items,
    });

渲染应该使用this.state.hiddenWord返回hiddenWord

<Text style={styles.wordtoGuess}>{this.state.hiddenWord}</Text> 

试试看

【讨论】:

  • 谢谢!我认为这解决了我的问题。我错过了我需要包含“This.state”。在我想在渲染时更新的变量中。
  • 嗨~如果有帮助,可以accept an answer,点击投票按钮下方的“复选标记”按钮,然后投票给答案,谢谢:)
猜你喜欢
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2023-01-16
  • 2017-10-22
相关资源
最近更新 更多