react学习笔记--搜索用户+pubsubjs

react学习笔记–搜索用户

这个搜索用户 之间需要把搜索的应用到下面的兄弟组件中,第一个方法采用的是props传给父组件,在回传给兄弟组件,这个方法比较麻烦,而使用pubsubjs工具库可解决这个问题,第二种方法简单应用了一下,GitHub上有对这个库的使用方法的解释。
index.js

import React from 'react';
import ReacDOM from 'react-dom';
import App from './components/app';
import './index.css';

ReacDOM.render(<App/>, document.getElementById('root'));
  • app.jsx
/* eslint-disable jsx-a11y/alt-text */
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>
                <div className = "container">
                    <Search setSearchName ={this.setSearchName}/> 
                    <Main searchName = {this.state.searchName}/>
                </div>
            </div>
        );
    }
}
  • main.jsx 内容组件
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable react/jsx-no-target-blank */
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: null,
        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,
                    avatarUrl: item.avatar_url
                }
            ))
            this.setState({
                loading: false,
                users
            })
        })
        .catch(error => {
            this.setState({
                loading:false,
                errorMsg: '失败'
            
            })
        })
    }

    componentDidMount() {

    }
    render() {
        const { initView, loading, users, errorMsg } = this.state;
        const { searchName } = this.props;
        if (initView) {
            return <h2>请出入关键字搜索:{searchName}</h2>
        } else if (loading) {
            return <h2>loading....</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>
            )
        }

    }
}
  • search.jsx 搜索组件
import PropTypes from 'prop-types';
import React, { Component } from 'react';

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 (
            <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.search}>Search</button>
                </div>
            </section>
        );
    }
}

使用pubsubjs库的话,不需要再设置一堆函数和状态,只需要发布(publish)和 订阅(subscribe)就ok了

  • search.jsx中search改为如下,不需要状态和设置propsType
	  search = () => {
        //得到输入的关键字
        const searchName = this.input.value.trim();
        if(searchName){
            PubSub.publish('search',searchName);
        }
        // 搜索
    }
  • main.jsx 这个方法改为如下,其他基本不变。
 componentDidMount() {
        PubSub.subscribe('search', (msg, searchName) => {
            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,
                        avatarUrl: item.avatar_url
                    }
                ))
                this.setState({
                    loading: false,
                    users
                })
            })
            .catch(error => {
                this.setState({
                    loading: false,
                    errorMsg: '失败'

                })
            })
        })
    }
发布了84 篇原创文章 · 获赞 204 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44983621/article/details/101320384
今日推荐