React组件间通信-sub/pub机制

React生命周期第二个demo演示了兄弟组件的通信,需要通过父组件,比较麻烦;下面介绍sub/pub机制来事项组件间通信。

项目结构:

React组件间通信-sub/pub机制

1、导包

npm i pubsub-js

React组件间通信-sub/pub机制

2、UserSearch.jsx

import React from 'react'
import PubSub from 'pubsub-js' export default class UserSearch extends React.Component {
state = {
keyword: ''
} render() {
const { keyword, userList } = this.state
return (
<div>
<h3>搜索用户</h3>
<input type="text" placeholder="请输入搜索关键字" name="keyword" value={keyword} onChange={(e) => this.keywordInputOnChangeHandler(e)} />
<input type="button" value="开始搜索" onClick={() => this.searchClickHandler()} />
</div>
)
} keywordInputOnChangeHandler = (e) => {
const keyword = e.target.value
this.setState({ keyword })
} searchClickHandler = () => {
const { keyword } = this.state
console.log(`keyword.trim()=${keyword.trim()}`)
if (!keyword.trim()) return // publish a topic asynchronously
PubSub.publish('search', keyword);
}
}

3、UserList.jsx

import React from 'react'
import PubSub from 'pubsub-js'
import Axios from 'axios' export default class UserList extends React.Component {
state = {
userList: []
} componentDidMount() {
var mySubscriber = (msg, data) => {
console.log(msg, data);
console.log(`订阅search,接收到消息:${data}`)
this.doSearch(data)
}; console.log('UserList组件钩子函数componentDidMount。。。');
PubSub.subscribe('search', mySubscriber)
} doSearch = (keyword) => {
Axios.get(`http://localhost:4000/react-db-crud/user/search?keyword=${keyword}`)
.then(res => {
if (res.data.code == 0) {
const userList = res.data.data
console.log(`userList=${JSON.stringify(userList)}`)
this.setState({ userList })
}
})
} render() {
return (
<div>
{
this.state.userList.map(user => <p>{user.id + "--" + user.name + "--" + user.age}</p>)
}
</div>
)
}
}
上一篇:JS对象 向上取整ceil() ceil() 方法可对一个数进行向上取整。 语法: Math.ceil(x) 注意:它返回的是大于或等于x,并且与x最接近的整数。


下一篇:JavaScript数据类型 Math对象详解