【React学习】github用户搜索案例,附触底刷新

话不多说直接上代码,困困=.=

app.jsx文件:

import axios from 'axios'
import React, { Component } from 'react'
// axios.defaults.baseURL = 'http://127.0.0.1:3000'
import './app.css'

export default class App extends Component {
  inputRef = React.createRef()
  botRef = React.createRef()
  state = {
    list: [],
    loading: false,
    page:1
  }
  componentDidMount() {
    window.onscroll = () => {
      if (this.botRef.current.offsetTop - window.pageYOffset < window.innerHeight + 100) {
        if(this.state.loading)return
        this.getUserInfo()
      }
    }
  }
  getUserInfo = () => {
    if (this.inputRef.current.value.trim() === '') return this.inputRef.current.value = ''
    this.setState({
      loading: true
    })
    axios.get('http://localhost:3000/api1/search/users', {
      params: {
        q: this.inputRef.current.value,
        page:this.state.page
      }
    }).then(res => {
      this.setState({
        list: this.state.list.concat(res.data.items),
        loading: false,
        page:this.state.page + 1
      })
    }, err => {
      console.log(err)
      this.setState({
        loading: false
      })
    })
  }
  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} placeholder='请输入用户信息关键字' style={{ width: '50vw' }} />
        <button onClick={this.getUserInfo} style={{ backgroundColor: '#903', marginLeft: '20px', color: 'white' }}>搜索</button>
        <div className='out-box'>
          {
            this.state.list.map(i => (
              <div className='column-flex' key={i.id}>
                <a rel="noreferrer" href={i.html_url} target="_blank">
                  <img src={i.avatar_url} alt="head_img" style={{ width: '100px' }} />
                </a>
                <p>{i.login}</p>
              </div>
            ))
          }
        </div>
        <div style={{ marginTop: '20px', display: this.state.loading ? 'block' : 'none' }}>
          <h1>Loading...</h1>
        </div>
        <div ref={this.botRef}></div>
      </div>
    )
  }
}

app.css样式文件:

.out-box{
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(3,1fr);
  grid-template-rows: minmax(100px,auto);
  row-gap: 10px;
  column-gap: 10px;
  padding: 10px;
  border: 2px solid #903;
}
.column-flex{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 2px solid orange;
}

setupProxy.js代理配置:

const {createProxyMiddleware} = require('http-proxy-middleware')

module.exports = function(app){
  app.use(
    createProxyMiddleware('/api1',{
      target:'https://api.github.com',
      changeOrigin:true,
      pathRewrite:{
        '^/api1':''
      }
    })
  )
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值