react消息的发布于订阅

使用消息的发布订阅模式,可以实现任意组件之间的通信

import PubSub from "pubsub-js";

订阅端:

import React, { Component } from "react";
import PubSub from "pubsub-js";
import "./index.css";

export default class index extends Component {
  state = {
    users: [],
    isFirst: true,
    isLoading: false,
    err: "",
  };

  // 在页面挂载完之后就进行订阅消息
  componentDidMount() {
    // 订阅消息
    this.token = PubSub.subscribe("hjh", (_, stateObj) => {
      this.setState(stateObj);
    });
  }

  //当组件被销毁时,需要将订阅取消调
  componentWillUnmount() {
    PubSub.unsubscribe(this.token);
  }

  render() {
    const { users, isFirst, isLoading, err } = this.state;

    return (
      <div className="row">
        {/* 此处三目表达式可以写成多个连起来的 */}
        {isFirst ? (
          <h2>欢迎使用,输入关键词进行搜索.....</h2>
        ) : isLoading ? (
          <h2>Loading......</h2>
        ) : err ? (
          <h2 style={{ color: "red" }}>{err}</h2>
        ) : (
          users.map((userObj) => {
            return (
              <div className="card" key={userObj.id}>
                <a rel="noreferrer" href={userObj.html_url} target="_blank">
                  <img
                    title="heade_picture"
                    src={userObj.avatar_url}
                    style={{ width: "100px" }}
                  />
                </a>
                <p className="card-text">{userObj.login}</p>
              </div>
            );
          })
        )}
      </div>
    );
  }
}

发布消息端:

import React, { Component } from "react";
import axios from "axios";
import PubSub from "pubsub-js";

export default class Search extends Component {
  search = () => {
    const { value } = this.kerWordElemet;
    // const {
    //   kerWordElemet: { value },
    // } = this;
     // 发布消息
    PubSub.publish("hjh", { isFirst: false, isLoading: true });
    axios.get(`https://api.github.com/search/users?q=${value}`).then(
      (response) => {
        // 发布消息
        PubSub.publish("hjh", {
          isLoading: false,
          users: response.data.items,
        });
      },
      (error) => {
        console.log("失败了", error);
         // 发布消息
        PubSub.publish("hjh", { isLoading: false, err: error.message });
      }
    );
  };

  render() {
    return (
      <div>
        <section className="jumbotron">
          <h3 className="jumbotron-heading">Search Github Users</h3>
          <div>
            <input
              ref={(c) => {
                this.kerWordElemet = c;
              }}
              type="text"
              placeholder="enter the name you search"
            />
            &nbsp;<button onClick={this.search}>Search</button>
          </div>
        </section>
      </div>
    );
  }
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量化接口stockapi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值