0
点赞
收藏
分享

微信扫一扫

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

成义随笔 2022-04-22 阅读 45

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

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)
      })
      this.setState({
        loading: false
      })
      this.setState({
        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':''
}
})
)
}
举报

相关推荐

0 条评论