React.js fetch请求JSON文件时URL编码字符未自动解码如何解决?
问题原因
你存储在JSON文件中的文本本身就是URL编码后的内容,fetch仅负责完成HTTP请求和响应接收,response.json()仅负责将符合JSON格式的响应内容转换为JavaScript对象,两个流程都不会自动识别并解码字符串内的URL编码字符,因此渲染时会直接输出原始编码内容。
解决方案
推荐在拿到JSON数据后统一完成解码再存入state,不需要修改后续渲染逻辑,实现成本最低:
修改你的getData方法中处理响应的逻辑,用JS原生的decodeURIComponent方法对所有编码字段做解码:
const getData = () => { fetch('questions.json', { headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }) .then(function (response) { return response.json() }) .then(function (myJson) { // 批量解码所有问题的编码字段 const decodedQuestions = myJson.map(questionItem => { return { // 保留无需解码的字段 ...questionItem, // 对编码的字符串字段逐一解码 category: decodeURIComponent(questionItem.category), question: decodeURIComponent(questionItem.question), correct_answer: decodeURIComponent(questionItem.correct_answer), // 遍历解码错误选项数组 incorrect_answers: questionItem.incorrect_answers.map(answer => decodeURIComponent(answer)) } }) setQuestions(decodedQuestions) }) }
如果不想修改数据请求逻辑,也可以封装一个简易的解码工具函数,在渲染时调用:
// 定义工具函数 const decodeText = (text) => decodeURIComponent(text) // 渲染时使用,比如: <p>{decodeText(questions[0].category)}</p> <div className='question'>{decodeText(questions[0].question)}</div> <button className='buttons'>{decodeText(questions[0].correct_answer)}</button>
两种方案都可以正常完成URL编码的解析,输出正常可读的文本内容。
内容的提问来源于stack exchange,提问作者The 3D Bank
相关产品推荐
相关产品推荐

