使用消息的发布订阅模式,可以实现任意组件之间的通信
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"
/>
<button onClick={this.search}>Search</button>
</div>
</section>
</div>
);
}
}