【发布时间】:2021-06-25 13:34:04
【问题描述】:
我正在开发 React Native 应用程序,在开始之前必须是覆盖视图。比如“欢迎画面”。在覆盖视图中阅读完内容后,按确定。
setState 不工作。抛出错误TypeError: _this.setState is not a function
我会尝试像这样使用 setState:
removeElement = () => {
//this.state.loadingScreen = false;
this.setState({
loadingScreen: false
})
console.log(`Staten arvo nyt: ` + this.state.loadingScreen);
当我使用 setState 时,它应该重新渲染组件,但我不知道它不起作用的原因是什么。我可以更改状态this.state.loadingScreen = false;,但它不会重新渲染。 forceUpdate() 也不工作。
问题:如何再次渲染组件以摆脱覆盖视图?
我的代码:
import React, { useState, setState, Component } from "react";
import { Text, View, StyleSheet, TextInput, Button, Alert, TouchableOpacity} from "react-native";
import AsyncStorage from '@react-native-community/async-storage';
export default function StartPage({ navigation }) {
state = {
loadingScreen: true,
}
let userInput = "";
let userInputName = "";
readUserInput = (text) => {
userInput = text
}
readUserInputName = (text) => {
userInputName = text
}
checkUserInput = () => {
if(userInput.length < 1 && userInputName.length < 1){
Alert.alert("Tarkista rekisterinumero ja nimi")
}
else{
storeData = async () => {
try{
AsyncStorage.setItem("RegistrationNumber", userInput);
AsyncStorage.setItem("UserName", userInputName);
}
catch(e){
console.log(e);
}
}
storeData();
navigation.navigate("GeneralInspection")
}
}
renderElement = () =>{
if(this.state.loadingScreen == true)
return <View style={styles.fullScreen}>
<TouchableOpacity style={styles.button} onPress={this.removeElement}>
<Text style={{fontSize:20}}>Change state to false</Text>
</TouchableOpacity>
</View>;;
return null;
}
removeElement = () => {
this.state.loadingScreen = false
}
setTimeout(
function() {
}
.bind(this),
1000
);
return (
<View style={styles.view}>
{ this.renderElement() }
<Text style={styles.text}>Tiedot</Text>
<TextInput
style={styles.inputStyle}
placeholder="Nimi"
onChangeText={this.readUserInputName}
autoCapitalize="words"
/>
<TextInput
style={styles.inputStyle}
placeholder="ABC-123"
onChangeText={this.readUserInput}
autoCapitalize="characters"
/>
<TouchableOpacity style={styles.button} onPress={this.checkUserInput}>
<Text style={{fontSize:20}}>Aloita</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
view: {
height: "100%",
width: "100%",
justifyContent: "center",
alignItems: "center",
},
text: {
fontSize: 40,
fontWeight: "bold",
padding:10,
fontStyle:"italic"
},
inputStyle: {
height:50,
borderColor:"black",
borderWidth:1,
width:"50%",
marginBottom:15,
textAlign:"center",
fontSize: 20,
borderRadius:5,
},
button: {
backgroundColor:"#007bff",
borderRadius:5,
padding:8,
width:"50%",
height: 60,
alignItems:"center",
justifyContent: "center",
},
fullScreen: {
height: "100%",
width: "100%",
zIndex: 100,
position: "absolute",
backgroundColor: "red",
}
});
【问题讨论】:
-
在功能组件中你必须使用
useState钩子来处理状态docs -
好吧,原因是我使用功能组件,而 setState 只在类中工作?
标签: react-native