业务逻辑流程
我们从搜索js中 查询的消息返回的数据 返回到list.js中展示 通过 pubsub-js 发送数据
Search.js代码
import React, { Component } from "react";
import PubSub from "pubsub-js";
class Search extends Component {
Search = async () => {
const {
keyWordElement: { value: keyWord },
} = this;
PubSub.publish("suzhou", { isFirst: false, isLoading: true });
try{
const responses = await fetch(`http://localhost:3000/api/search/users?q=${keyWord}`);
const data = await responses.json()
PubSub.publish('suzhou',{isLoading:false,user:data.items})
}catch(error){
PubSub.publish('suzhou',{isLoading:false,err:error.message})
console.log('请求出错',error)
}
};
render() {
return (
<section className="jumbotron">
<h3 className="jumbotron-heading">请输入您要搜索的内容</h3>
<div>
<input
ref={(c) => (this.keyWordElement = c)}
type="text"
placeholder="enter the name you search"
/>
<button onClick={this.Search}>搜索</button>
</div>
</section>
);
}
}
export default Search;
List.js界面
import React, { Component } from "react";
import "./index.css";
import PubSub from 'pubsub-js'
class List extends Component {
state = {
user: [],
isFirst: true,
isLoading: false,
err: ''
}
//(装载完成),在render之后调用
componentDidMount() {
this.token = PubSub.subscribe("suzhou", (_, dataObj) => {
this.setState(dataObj);
});
}
componentWillUnmount() {
PubSub.unsubscribe(this.token);
}
render() {
const { user, isFirst, isLoading, err } = this.state;
return (
<div className="row">
{isFirst ? (
<h2>欢迎来到这里</h2>
) : isLoading ? (
<h2>正在加载...</h2>
) : err ? (
<h2 style={{ color: "red" }}>{err}</h2>
) : (
user.map((userObj) => {
return (
<div key={userObj.id} className="card">
<a rel="noreferrer" href={userObj.html_url} target="_blank">
<img
alt="head_portrait"
src={userObj.avatar_url}
style={{ width: "100px" }}
/>
</a>
<p className="card-text">{userObj.login}</p>
</div>
);
})
)}
</div>
);
}
}
export default List;