从 Render 调用函数 - React
Calling a function from Render - React
我正在尝试在渲染函数中调用一个名为 makeMap 的函数。一切都被打印到控制台,但是,它不会更新 HTML。很想知道我做错了什么以及正确的方法是什么。 :)
import React from "react";
import axios from "axios";
export default class CountryList extends React.Component {
state = {
countries: []
}
componentDidMount() {
axios.get(`https://restcountries.com/v2/all?fields=name,region,area`)
.then(res => {
const countries = res.data;
this.setState({ countries });
})
}
makeMap() {
this.state.countries.map(country => {
console.log("aaaaaaaaa");
return (<li key={country.name}>{country.name}</li>)
})
}
render() {
return(
<div>
{this.makeMap()}
</div>
)
}
}
您可以更改 makeMap()
功能,如下所示:
makeMap() {
return this.state.countries.map(country =>
(<li key={country.name}>{country.name}</li>)
)
}
我正在尝试在渲染函数中调用一个名为 makeMap 的函数。一切都被打印到控制台,但是,它不会更新 HTML。很想知道我做错了什么以及正确的方法是什么。 :)
import React from "react";
import axios from "axios";
export default class CountryList extends React.Component {
state = {
countries: []
}
componentDidMount() {
axios.get(`https://restcountries.com/v2/all?fields=name,region,area`)
.then(res => {
const countries = res.data;
this.setState({ countries });
})
}
makeMap() {
this.state.countries.map(country => {
console.log("aaaaaaaaa");
return (<li key={country.name}>{country.name}</li>)
})
}
render() {
return(
<div>
{this.makeMap()}
</div>
)
}
}
您可以更改 makeMap()
功能,如下所示:
makeMap() {
return this.state.countries.map(country =>
(<li key={country.name}>{country.name}</li>)
)
}