我想使用axios从随机用户API中获取性别为女性的随机用户
我尝试了.filter,.select但没有用。
componentDidMount() {
axios
.get("https://randomuser.me/api/?results=5")
.filter(function(i, n) {
return n.gender === "female";
})
.then(response =>
response.data.results.map(user => ({
name: `${user.name.first} ${user.name.last}`,
username: `${user.login.username}`,
email: `${user.email}`,
image: `${user.picture.thumbnail}`,
gender: `${user.gender}`
}))
)
.then(users => {
this.setState({
users,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
const { isLoading, users } = this.state;
return (
<React.Fragment>
<h2>Brief list</h2>
<div>
{!isLoading ? (
users.map(user => {
const { username, name, email, image, gender } = user;
return (
<div key={username}>
<p>{name}</p>
<div>
<img src={image} alt={name} />
</div>
<p>{gender}</p>
<p>{email}</p>
<hr />
</div>
);
})
) : (
<p>Loading...</p>
)}
</div>
</React.Fragment>
);
}
}
我只想显示女性用户
答案 0 :(得分:0)
您应该在.filter
函数中编写.then
,因为axios
返回了一个Promise。
componentDidMount() {
axios.get("https://randomuser.me/api/?results=5")
.then(function(data){
let femaleData = data.results.filter(function(n) { return n.gender === "female"; }) })
答案 1 :(得分:0)
如果仅显示female
,则应更新api url参数,以便不需要其他过滤器。
仅适用于用户(限制5)
https://randomuser.me/api/?results=5
仅适用于女性用户(限制5)
https://randomuser.me/api/?results=5&&gender=female
答案 2 :(得分:0)
在尝试映射时,您必须在映射之前过滤响应,但是您应该在.then
内进行响应。因此您的componentDidMount
应该是这样的:
componentDidMount() {
axios
.get("https://randomuser.me/api/?results=5")
.then(response =>
response.data.results.filter(item => item.gender === "female")
)
.then(femaleUsers =>
femaleUsers.map(user => ({
name: `${user.name.first} ${user.name.last}`,
username: `${user.login.username}`,
email: `${user.email}`,
image: `${user.picture.thumbnail}`,
gender: `${user.gender}`
}))
)
.then(users => {
this.setState({
users,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}