我尝试仅获取此 API 链接中的名称区域,但它向我显示 setState
属性中的错误。语法问题还是其他问题?
顺便问一下:为什么我要用这个案例, map 函数?供将来使用。
谢谢!
应用程序 Js:
import React from 'react';
import './App.css';
import Region from './region';
import {BrowserRouter,Switch,Route} from "react-router-dom";
function App() {
return (
<div className="App">
<BrowserRouter>
<Switch>
<Route exact path = "/" component={Region}/>
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
组件:
import React, { Component } from "react";
class Region extends Component {
constructor (props) {
super (props)
this.state = {
items:[],
isLoad:false
}
}
ComponentDidMount () {
fetch("https://restcountries.eu/rest/v2/region/europe").then(res=>res.json()).then(JSON=> {
this.setState ({
isLoad = true,
items = JSON,
})
})
}
render () {
let {isLoad,items} = this.state;
if(!isLoad) {
return <div>Loading...</div>
}
else {
return <div>
<ul>
{items.map(items=>(
<li key={items.name}> </li>
))}
</ul>
</div>
}
}
}
export default Region;
最佳答案
.map()
背后的原因是您有机会通过访问每个元素并返回不同的方式、结构来操作数组元素。在 React 情况下,它有助于为 render()
方法渲染正确的 JSX 元素。建议阅读Lists and Keys来自React的官方文档。
读取自Array.prototype.map()
文档:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
第一个问题是错误地将属性传递给 setState()
,请注意,我使用的是 :
而不是 =
。尝试更改如下:
this.setState({
isLoad: true,
items: JSON,
});
此外,您可以尝试以下操作 - 当前元素的名称与数组本身相同 - 最好使用不同的名称:
return <div>
<ul>
{items && items.map(e => <li key={e.name}> {e.name} </li>)}
</ul>
</div>
希望对您有所帮助!
关于javascript - 在 React Router 中加载 JSON 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60158919/