React调用随机单词API遇问题:点击按钮后无单词显示
问题修复指南
核心问题点
- 初始状态语法错误:
state里的[test]是未定义变量,应写成字符串数组['test'],否则会触发语法报错。 - Fetch响应未解析:
fetch返回的response是原生响应对象,并非接口返回的JSON数据,必须调用.json()方法解析后才能拿到单词数组。
修复后的完整代码
export default class WordGenerator extends React.Component { state = { wordToShow: ['test'], } componentDidMount(){ this.changeWordToShow() } changeWordToShow = () => { fetch('https://random-word-api.herokuapp.com/word?lang=it') .then(response => response.json()) .then(data => this.setState({ wordToShow: data })) .catch(error => { console.error('获取单词失败:', error); this.setState({ wordToShow: ['获取失败'] }); }); } render(){ return ( <View style={Styles.container}> <Text style={Styles.paragraph}> {this.state.wordToShow[0]} </Text> <Button title="Change word" onPress={() => this.changeWordToShow()}/> </View> ); } }
补充说明
- 新增
catch块处理请求异常,避免网络问题或接口故障导致页面无响应。 - 初始状态保持数组格式,和接口返回的数据结构一致,保证渲染逻辑统一。
内容的提问来源于stack exchange,提问作者Batchounet
相关产品推荐
相关产品推荐

