【发布时间】:2021-12-08 16:00:30
【问题描述】:
const jsonUrlExternal = require('https://reactnative.dev/movies.json'); //this works
const jsonUrlLocal = require('../../json/MOCK_DATA.json'); //this doesn't work
当我使用第一个 const jsonUrlExternal 时,我的应用程序运行良好并以 JSON 格式获取数据。但是,当我只是将 URL 更改为本地路径时,它会给我一个错误:Type Error: Network request failed。下面是我用来获取本地和外部 JSON 文件的代码:
const [data, setData] = useState([]);
useEffect(() => {
fetch(jsonUrlLocal) //the error appears exactly when i write this line
.then((response) => response.json())
.then((json) => setData(json.movies))
.catch((error) => alert(error))
})
这是我用来显示来自 JSON 的数据的 FlatList:
<FlatList
data={data}
keyExtractor={({id}, index) => id}
renderItem={({item}) => (
<Text>
{item.title}, {item.realeseYear}
</Text>
)}
/>
简而言之:当我使用来自 URL 的外部 JSON 时,我的 FlatList 可以工作,但是当我只是将 URL 更改为本地 path/to/the/file/ 时,应用程序会返回错误消息:Type Error: Network request failed。
OBS:本地 JSON 中的内容正是 ExternalJson 的 RAW Copy。我确定本地 JSON 没有输入错误。
【问题讨论】:
-
您不只是正常导入 JSON 文件(使用顶级导入)是否有原因?该文件已经存在,您不会从其他地方获取它。
标签: json typescript react-native fetch