React Native报错Cannot read property 'state' of undefined新手求助
报错核心原因
你当前写的是React函数式组件,但是混用了类组件的专属语法:
- 函数组件不存在
constructor构造方法,你定义的这个方法根本不会执行 - 函数组件中没有
this关键词,所以所有this.state、this.setState的调用都会因为this是undefined触发报错。
完整修复代码
import React, { useState } from "react"; import { StyleSheet, Button, Text, TextInput, View } from "react-native"; export default function GetSummonerInfo(props) { // 用useState声明所有需要的状态 const [url] = useState("https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"); const [apikey] = useState(props.apikey); const [text, setText] = useState("StanLachie"); const [name, setName] = useState(null); const [summonerLevel, setSummonerLevel] = useState(null); function handlePress() { let requestUrl = url + text + "?api_key=" + apikey; fetch(requestUrl) .then((response) => response.json()) .then((responseJson) => { // 直接调用useState返回的更新方法修改状态 setName(responseJson.name); setSummonerLevel(responseJson.summonerLevel); return responseJson; }) .catch((error) => { console.error(error); setName("Player Not Found!"); setSummonerLevel("N/A"); }); }; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="Summoner name" value={text} onChangeText={(inputText) => setText(inputText)} /> <Button color="#841584" onPress={handlePress} title={`Search Stats For "${text}"`} /> {name != null && ( <View> <Text>Summoner Name : {name}</Text> <Text>Summoner Level : {summonerLevel}</Text> </View> )} </View> ); } const styles = StyleSheet.create({ input: { padding: 10, borderColor: "grey", borderWidth: 1, }, container: { margin: 10, }, label: { fontWeight: "bold", margin: 10, }, });
主要修改点说明
- 导入
useStateHook,这是React函数组件用来管理状态的标准API - 组件名首字母改为大写,符合React组件命名规范
- 移除了所有和
this相关的写法,函数组件不需要用this访问内部变量和方法 - 每个状态都通过
useState声明,会返回当前状态值和修改状态的方法,直接调用修改方法即可更新状态、触发组件重新渲染 - 修复了输入框的绑定逻辑,输入内容会实时更新到
text状态 - 修复了按钮标题显示逻辑,会展示当前输入的召唤师名称
内容的提问来源于stack exchange,提问作者StanLachie
相关产品推荐
相关产品推荐

