组件之间的通信
——Publish-subscribe mode (pubsubJs)
Components suitable for sibling components or other patterns (passing data)
The third-party package axios is used in this project, which is used to realize front-end and back-end interaction
At the same time, another third-party package pubsub-js is also used, which implements the publish and subscribe mode.
一、准备工作:
1. Create the myProject04 project directory.
2. Create a manifest file. npm init -y
3. Create the required third-party dependencies. npm install react react-dom react-scripts axios pubsub-js --save
4. Create a public folder under the project directory, and create index.html under this folder.
5. Create a src folder under the project directory, and create under this folder:
(1) Entry file index.js;
(2) Outer component App.js;
(3)GoodList.jsx;
(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>
)
}
}
三、运行命令
Simplified version:
Add a line command "start" to the manifest file : "react-scripts start"
Run the command: npm start
"scripts": {
"start": "react-scripts start",
"test": "echo \"Error: no test specified\" && exit 1"
}