组件之间的通信
——发布-订阅模式(pubsubJs)
适用于兄弟组件或其他模式的组件(传递数据)
在该工程中用到了第三方包axios,该包用于实现前后端交互
同时也用到了另一个第三方包pubsub-js,该包实现了发布订阅模式。
一、准备工作:
1、创建myProject04工程目录。
2、创建清单文件。 npm init -y
3、创建需要的第三方依赖。 npm install react react-dom react-scripts axios pubsub-js --save
4、在工程目录下创建public文件夹,在该文件夹下创建index.html。
5、在工程目录下创建src文件夹,在该文件夹下创建:
(1)入口文件index.js;
(2)外层组件App.js;
(3)GoodList.jsx;
扫描二维码关注公众号,回复:
14871076 查看本文章
(4)SearchBox.jsx
二、编写代码:
1、index.html
<div id="root"></div>
2、App.js
import React, {
Component } from 'react'
import SearchBox from './SearchBox'
import GoodsList from './GoodsList'
export default class App extends Component {
render() {
return (
<div>
<SearchBox/>
<GoodsList/>
</div>
)
}
}
3、GoodsList.jsx
import React, { Component } from 'react'
import Pubsub from 'pubsub-js'
import axios from 'axios'
export default class GoodsList extends Component {
state = {
page: 1,
goods: []
}
// 钩子函数内部写订阅 先订阅 然后等着发布方发布 接收数据
componentDidMount() {
// 首次渲染显示第一页
this.getData(1)
// 搜索时根据输入的页码再次调用 --- 订阅 pageNumber由自己定义 要与发布方一致
Pubsub.subscribe('pageNumber', (msg, data) => {
this.getData(data)
})
}
// 封装axios
getData = (page) => {
axios.get(`https://api.shop.eduwork.cn/api/index?page=${page}`)
.then(res => {
if (res.status === 200) {
this.setState({
page: res.data.goods.current_page,
goods: res.data.goods.data
})
}
})
}
// 查询
render() {
return (
<div>
{
this.state.goods.map(e =>
<div className='item' key={e.id}>
<h3>{e.title}</h3>
<img src={e.cover_url} />
</div>
)
}
</div>
)
}
}
4、SearchBox.jsx
import React, { Component } from 'react'
import Pubsub from 'pubsub-js'
export default class SearchBox extends Component {
state = {
page: 1,
}
// 定义ref
QueryNumber = React.createRef()
// 通常都是操作一个发布 发布方
queryPage = () => {
Pubsub.publish('pageNumber', this.QueryNumber.current.value)
this.setState({
page: this.QueryNumber.current.value
})
}
render() {
return (
<div>
<input type="text" placeholder='请输入页码' ref={this.QueryNumber} />
<input type="button" value="查询" onClick={this.queryPage} />
<h3>当前页:{this.state.page}</h3>
</div>
)
}
}
三、运行命令
简化版:
在清单文件中添加一行命令 “start”: “react-scripts start”
运行命令:npm start
"scripts": {
"start": "react-scripts start",
"test": "echo \"Error: no test specified\" && exit 1"
}