react -实现用户搜索

1. 效果

react -实现用户搜索_第1张图片

2.会用到组件的生命周期

react -实现用户搜索_第2张图片

3.数组的map方法

 可以只保留json返回对象里指定的对象的值

react -实现用户搜索_第3张图片

react -实现用户搜索_第4张图片

4.静态组件

5. app.jsx

import React, {Component} from 'react'
import PropTypes from 'prop-types'
import Search from './search'
import Main from './main'



export default class Page extends Component{
    state={
        searchName:''
    }
    setSearchName=(searchName) => {
       this.setState({searchName})
    }
    render(){
      
        return(
            

search

) } }

6.  main.jsx

import React, {Component} from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'

export default class Main extends Component{
    static propTypes={
        searchName:PropTypes.string.isRequired
    }
    state={
        initView:true,
        loading:false,
        users:{url:'',avataUrl:'',name:'tom'},
        errorMsg:null
    }

    // 当组件接收到新的属性时调用,发请求
    componentWillReceiveProps(newProps){
        const {searchName}=newProps
        // 发请求之前先更新状态
        this.setState({
            initView:false,
            loading:true
        })
        // 发请求
        const url=`https://api.github.com/search/users?q=${searchName}` 
        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,
                    avataUrl:item.avatar_url
                }))
                console.log(users);
                // 更新状态
                this.setState({
                    loading:false,
                    users
                })
            })
            .catch(error => {
                // 失败的更新状态
                this.setState({
                    errorMsg:error.message
                })
            })
    }

    render(){
        const {initView, loading, users, errorMsg}= this.state
        const {searchName}=this.props
        if(initView){
            return (
                
请输入关键字搜索: {searchName}
) }else if(loading){ return (
正在请求中...
) }else if(errorMsg){ return (
{errorMsg}
) }else{ return(
{ users.map((user,index) => (

{user.name}

)) }
) } } }

7. search.jsx

import React, {Component} from 'react'
import PropTypes from 'prop-types'

export default class Search extends Component{
    static propTypes={
        setSearchName:PropTypes.func.isRequired
    }
    search= ()=> {
        const searchName=this.input.value.trim()
        if(searchName){
            this.props.setSearchName(searchName)
        }
            
    }
    render(){
       
        return (
            
this.input =input} />
) } }

 

你可能感兴趣的:(react)