You need to enable JavaScript to run this app. React state中存储的JSON对象无法读取,取索引返回[符号如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React state中存储的JSON对象无法读取,取索引返回[符号如何解决?

问题解决方案

核心原因

  • 你请求的本地文件没有.json后缀,服务端返回的内容类型为纯文本,axios不会自动将其解析为JavaScript数组,response.data实际是JSON格式的字符串,你取字符串第0位自然返回字符[。
  • state初始化类型错误:你在constructor中将questions的初始值设为空字符串'',不符合后续存储数组的类型预期。同时render函数中你先执行了解构、打印操作,再判断isLoading加载状态,加载阶段就会触发字符串的下标读取逻辑。
  • 你提供的示例JSON内容不符合标准JSON规范:使用了反引号包裹字符串、键没有加双引号,会导致JSON解析失败。

具体修复步骤

  1. 修改本地文件配置
    将public/apis/questions文件重命名为public/apis/questions.json,同时修改文件内容为标准JSON格式:
[
    {
        "id": 0,
        "question": "What is the capital of Nigeria?",
        "options": ["New Delhi", "Abuja", "Aba", "Onisha"],
        "answer": "Abuja"
    },
    {
        "id": 1,
        "question": "What is the capital of India?",
        "options": ["Punjab", "Awka", "Owerri", "Enugu"],
        "answer": "New Delhi"
    }
]
  1. 修正state初始值
    修改constructor中questions的初始值为空数组:
constructor(props) {
    super(props);
    this.state = {
        showInstruction: true,
        questionIndex: 0,
        isLoading: true,
        questions: [] // 改为空数组
    };
}
  1. 调整axios请求逻辑
    修改请求路径,强制指定返回类型为JSON,合并setState操作减少不必要的渲染:
componentDidMount() {
    console.log("After mount! Let's load data from API...");
    axios({
        method: "GET",
        url: "/apis/questions.json",
        responseType: "json"
    }).then(response => {
        console.log(response.data);
        this.setState({ 
            questions: response.data,
            isLoading: false 
        });
    });
}
  1. 调整render函数执行顺序
    把加载状态判断放在数据操作之前,避免加载阶段执行无效逻辑:
render() {
    if (this.state.showInstruction) {
        return (
            <div>
                <h1>Welcome to Quiz</h1>
                <p>Quiz instructions goes here</p>
                <button type="button" onClick={this.proceedHandler}>Proceed</button>
            </div>
        )
    }
    // 先判断加载状态
    if (this.state.isLoading) {
        return <div className="App">Loading...</div>;
    }
    // 加载完成后再操作数据
    const { questions } = this.state;
    console.log(questions[0]); // 此时可以正常拿到第一个题目对象
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
                <div onChange={this.onChangeValue}>
                    <p>{questions[0].question}</p>
                    {questions[0].options.map(opt => (
                        <label key={opt}>
                            <input type="radio" name="answer" value={opt}/>
                            {opt}
                        </label>
                    ))}
                </div>
                <button onClick={this.handleQuestion}>Next</button>
            </form>
        </div>
    )
}

内容的提问来源于stack exchange,提问作者Ragu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 22:57:03