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
言語配列にアクセスする必要があります。これで、countryコンポーネント内の言語をマップしようとすると、情報を表示できます。しかし、モーダルコンポーネントでのみ言語を表示したいので、モーダルを担当するclickedCountry状態をマップすると、「言語」が未定義であるというエラーが表示されます。同じオブジェクトがfind関数でフィルタリングされた場合はどうなりますか?私が明確な人であったことを願っています、乾杯。
何が起こったのか理解できたと思います!これをモーダルコンポーネントに追加するだけです
<ul>
{
languages && languages.map(lan=> {return <li>{lan.name}</li>} )
}
</ul>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加