【发布时间】:2020-02-13 08:26:57
【问题描述】:
我必须读取一个json文件,我按照以下代码:stackoverflow
尝试评论中显示的示例,但它不适合我。
我必须阅读我在本地拥有的这个文件,但我没有成功。
你能帮帮我吗?
链接:Codesandbox
代码:
fetch("/user.json")
.then(res => res.json())
.then(res => res.results)
.then(res => {
console.log(res);
let u = res.map((suggestion, i) => ({
label: suggestion.email,
name: suggestion.name.first,
surname: suggestion.name.last,
address: suggestion.location.street.name,
email: suggestion.email,
picture: suggestion.picture.thumbnail
}));
let options =
inputLength === 0
? []
: u.filter(suggestion => {
const keep =
count < 5 &&
suggestion.label &&
suggestion.label.slice(0, inputLength).toLowerCase() ===
inputValue;
if (keep) count += 1;
return keep;
});
this.setState({ options });
})
.catch(e => console.log("Er:", e));
【问题讨论】:
-
有什么问题?现在发生了什么?预期的行为是什么?
-
我想阅读该文件。他没有阅读它并进入获取捕获条件。但是,如果您尝试我在codesandbox 上发布的示例,您会立即看到它。
-
user.json 文件在哪里?如果它在公共文件夹中,则获取 uri 参数应该是
${process.env.PUBLIC_URL} + "/user.json"实际上我尝试了您的 CodeSandbox 演示,它可以工作;但它不在您的本地环境中? -
我已经尝试打印 process.env.PUBLIC_URL 返回未定义。
-
请更新您的问题描述。
标签: javascript json reactjs fetch fetch-api