reactjs - 将 API 信息映射到 React 组件
问题描述
我正在尝试为用户存储库创建一个 Github 搜索并将它们显示在卡片中。我的 ListComponent 显示时看起来不错,但我无法将 repo 信息映射到每张卡。当我控制台记录数据时,它按预期显示,但不会映射到卡片。我使用 fetch 进行 api 调用,使用 lodash 进行映射。任何帮助,将不胜感激!
Github搜索:
import React, { Component, Fragment } from 'react';
import ListComponent from './ListComponent';
import _ from 'lodash';
class GithubSearch extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
repos: [],
apiMsg:'',
userInfo: {}
}
};
handleChange = (e) => {
this.setState({ username: e.target.value });
setTimeout(this.handleSubmit, 1000)
}
handleSubmit = () => {
fetch(`https://api.github.com/users/${this.state.username}/repos`)
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(err => {
this.setState({
repos: [],
apiMsg: err.message
})
})
}
render() {
return (
<Fragment>
<div className='header'>Github Search</div>
<form className='search'>
<input
placeholder='Github user'
name='github user'
type='text'
onChange={this.handleChange}
value={this.state.username}
/>
<button type='submit' onSubmit={this.handleSubmit}>Search</button>
</form>
<p>{this.state.apiMsg}</p>
<div className='right-container'>
{_.map(this.state.repos, repo => <ListComponent key={repo.id} {...repo}/>)}
</div>
</Fragment>
)
}
}
export default GithubSearch;
列表组件:
import React from 'react'
import '../App.css'
const ListComponent = ({ name, description, language, html_url }) => {
return (
<div className='card'>
<div className='card-body'>
<h2><a href={html_url} target='_blank' rel="noreferrer">{name}</a></h2>
</div>
<div className='card-body'>
<p>{description}</p>
</div>
<div className='card-body'>
<p>Languages: {language}</p>
</div>
</div>
);
}
export default ListComponent;
解决方案
您忘记在 API 响应后为 repo 设置状态,请尝试以下代码
handleSubmit = () => {
fetch(`https://api.github.com/users/${this.state.username}/repos`)
.then(res => res.json())
.then(data => {
console.log(data)
this.setState({repo:data})
})
.catch(err => {
this.setState({
repos: [],
apiMsg: err.message
})
})
}
推荐阅读
- sql - Firebird中的条件唯一索引
- android - 使用加速度计和磁场传感器寻找朝拜方向的逻辑
- android - 如何在 FloatingActionButton/Button Click 事件中使用协程
- django - Heroku 无法检测到我的 forms.py。“模块未找到错误在 /”
- python - Altair 中的聚合函数块图交互性
- jquery - 通过 Ajax 向 Laravel 控制器提交带有文本和图像的表单
- javascript - 是否可以将 PHP 查询变量传递给 JS 而不在 View Source 中显示它?
- bash - 在 Bash 中将 Matlab (Linux) 作为 Cron 作业运行的输出在电子邮件中包含许多“>>”
- assembly - 减去两个字符
- javascript - 如何防止表格数据元素合并到一列中?