我正在RestCountries Api的帮助下构建此应用程序,以便能够在网格上显示每个国家的基本详细信息,在单击每个框后,该应用程序将显示一个包含更多详细信息的模式。到目前为止,这就是我的代码:
class App extends React.Component{
constructor (props){
super (props);
this.state={
countries : [],
clickedCountry: {},
modalOn : false,
}
}
componentDidMount(){
axios.get(`https://restcountries.eu/rest/v2/all`)
.then(res => {
const data = res.data;
this.setState({
countries : data
})
let countries = this.state.countries
console.log(countries);
})
}
showInfo = (name) => {
this.setState({
clickedCountry : this.state.countries.find(it => it.name===name),
modalOn : true
});
}
closeModal =()=>{
this.setState({
modalOn : false
})
}
render() {
return (
<div className="container">
{this.state.countries.map(country=>
<Country name={country.name}
key={country.name}
population ={country.population}
region={country.region}
capital={country.capital}
flag={country.flag}
showInfo={this.showInfo}
languages={country.languages}
/>
)}
<div style={{display: this.state.modalOn? "block" : "none"}}>
<Modal closeModal={this.closeModal}
name={this.state.clickedCountry.name}
population={this.state.clickedCountry.population}
region={this.state.clickedCountry.region}
capital ={this.state.clickedCountry.capital}
flag={this.state.clickedCountry.flag}
nativeName ={this.state.clickedCountry.nativeName}
subregion={this.state.clickedCountry.subregion}
topLevelDomain={this.state.clickedCountry.topLevelDomain}
languages={this.state.clickedCountry.languages}
/>
</div>
</div>
)
}
}
模块组件:
const Modal = ({closeModal, name, population, region, capital, flag, languages, nativeName, subregion, topLevelDomain, currencies}) => {
return (
<div className="modal">
<div className="modal-content">
<span onClick={closeModal}>x</span>
<div className="img">
<img src={flag}/>
</div>
<p>{name}</p>
<p>Native name: {nativeName}</p>
<p>population: {population}</p>
<p>Region: {region}</p>
<p>Sub Region: {subregion}</p>
<p>Top level domain: {topLevelDomain}</p>
<p>Capital: {capital}</p>
</div>
</div>
)
}
到目前为止,我已经绘制了每个国家的地图,并且点击时的模式显示了更详细的信息。现在的问题是我需要在api中访问嵌套在对象内的数组:
area: 91
gini: null
timezones: ["UTC-04:00"]
borders: []
nativeName: "Anguilla"
numericCode: "660"
currencies: [{…}]
languages: [{…}]
translations: {de: "Anguilla", es: "Anguilla", fr: "Anguilla", ja: "アンギラ", it: "Anguilla", …}
flag: "https://restcountri
我需要访问语言数组。现在,如果我尝试在国家/地区组件中映射语言,则可以显示信息。但是我只想显示模态组件上的语言,如果我映射了负责模态的clickedCountry状态,我将收到“语言”未定义的错误。如果通过find函数过滤同一个对象,结果如何?希望我很清楚,欢呼。
答案 0 :(得分:0)
我知道您了解发生了什么!,只需将其添加到Modal组件
<ul>
{
languages && languages.map(lan=> {return <li>{lan.name}</li>} )
}
</ul>