React技术栈-react使用的Ajax请求库用户搜索案例

         React技术栈-react使用的Ajax请求库用户搜索案例

                                  作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

一.react使用的Ajax请求库用户搜索案例

1>.react脚手架项目结构

2>.目录中的代码

import React,{Component} from 'react';

import Search from "./search";
import Main from "./main";

export default class App extends Component{
    state = {
        searchName: ''
    }

    setSearchName = (searchName) =>{
        //更新状态
        this.setState({searchName})
    }

    render(){
        return (
            <div className="container">
                 <Search setSearchName = {this.setSearchName} />
                 <Main searchName={this.state.searchName}/>
                </div>
        )
    }
}
app.jsx文件内容
import React,{Component} from 'react';
import PropTypes from "prop-types";
import axios from 'axios';

export default class Main extends Component{

    //该组件类添加searchName属性,该属性的类型为"string",而且该属性是必须传递的。
    static propTypes = {
        searchName: PropTypes.string.isRequired
    }

    state = {
        //初始化状态
        initView: true,
        //搜索状态
        loading: false,
         //搜索到的内容
        users: null,
        //定义错误信息
        errorMsg: null
    }

    //当组件接收到新的属性时自动回调,
    componentWillReceiveProps(newProps) {
        //即指定了新的searchName,需要发送请求。
        const {searchName} = newProps;
        //更新状态(请求中)
        this.setState({
            initView:false,
            loading:true
        })
        //获取用户的url
        const url = `https://api.github.com/search/users?q=${searchName}`
        //发Ajax请求,此处外面使用axios发送Ajax请求,需要手动安装"npm install --save axios"
        axios.get(url)
            .then(response =>{
                //得到响应数据
                const result = response.data;
                // console.log(result);
                const users = result.items.map(item => ({name:item.login,url:item.html_url,avatarUrl:item.avatar_url}));
                //更新成功的状态
                this.setState({loading:false,users})

            })
            .catch(error =>{
                //更新失败的状态
                this.setState({loading:false,errorMsg:error.message})
            })
    }

    render(){
        const {initView,loading,users,errorMsg} = this.state;
        const {searchName} = this.props;

        if(initView) {
            return <h2>请输入关键字进行搜索</h2>
        }else if(loading) {
            return <h2>正在搜索中...</h2>
        }else if(errorMsg) {
            return <h2>{errorMsg}</h2>
        }else {
            return (
                <div className="row">
                    {
                        users.map((user,index) => (
                            <div className="card" key={index}>
                                <a href={user.url} target="_blank">
                                    <img src={user.avatarUrl}  style={{width:100}}/>
                                </a>
                                <p className="card-text">{user.name}</p>
                            </div>
                        ))
                    }
                </div>
                )
            }
        }
}
main.jsx文件内容
import React,{Component} from 'react';
import PropTypes from 'prop-types';

export default class Search extends Component{

    //该组件类添加setSearchName属性,该属性的类型为"func",而且该属性是必须传递的。
    static propTypes = {
        setSearchName: PropTypes.func.isRequired
    }

    handleSearch = () => {
        //得到输入的关键字
        const searchName = this.input.value.trim();
        //搜索
        if(searchName){
            //搜索
            this.props.setSearchName(searchName);
        }
    }

    render(){
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">Search Github Users</h3>
                <div>
                    <input type="text" placeholder="enter the name you search" ref={input => this.input = input}/>
                    <button onClick={this.handleSearch}>Search</button>
                </div>
            </section>
        )
    }
}
search.jsx文件内容
.album {
  min-height: 50rem; /* Can be removed; just added for demo purposes */
  padding-top: 3rem;
  padding-bottom: 3rem;
  background-color: #f7f7f7;
}

.card {
  float: left;
  width: 33.333%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: .75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
index.css文件内容
import React from "react";
import ReactDOM from "react-dom"
import App from "./components/app"

import './index.css'

//渲染组件
ReactDOM.render(<App />,document.getElementById("root"))
index.js文件内容

3>.启动项目

 

二.验证用户搜索功能

posted @ 2020-01-04 00:48  尹正杰  阅读(341)  评论(0编辑  收藏  举报