首页 > 解决方案 > 将 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;

标签: reactjsmappinglodashgithub-api

解决方案


您忘记在 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
            })
        })
    }

推荐阅读