You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React调用随机单词API遇问题:点击按钮后无单词显示

问题修复指南

核心问题点

  1. 初始状态语法错误:state里的[test]是未定义变量,应写成字符串数组['test'],否则会触发语法报错。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:05:42