概念
队列是JavaScript中的一种数据结构,遵循先进先出(FIFO / First In First Out)的规则。队列可以理解为食堂排队取餐的场景,先排队的取到餐后先去吃饭。
实现
class Queue {
constructor(items) {
this.items = items || []
}
// 入列
enqueue = ele => {
this.items.push(ele)
}
// 出列
dequeue = () => {
this.items.shift()
}
// 取队列第一个
getFront = () => {
return this.items[0]
}
// 清空队列
clear = () => {
this.items = [];
}
get size() {
return this.items.length;
}
get isEmpty() {
return !this.items.length;
}
}
export default Queue
实际应用场景
笔者最近在改项目bug时,遇到这么一个问题,我们项目的首页有多个Modal弹窗,这些弹窗的显示都是通过调用不同的接口去判断是否显示的,那么这样就带来了一个问题,当这几个弹窗的触发条件同时发生时,那这些弹窗就会重叠在一起,用户体验很不好。
那如何去优化这个问题,我也是想了许久,最后是想能否用队列去实现,尝试之后发现确实可行。这里我想到了两种方式去实现。
方式一:直接把组件推入队列,demo如下
import React from 'react';
import Queue from './Queue'
class App extends React.Component {
constructor(props) {
super(props)
this.queue = new Queue()
this.state = {
comp: null
}
}
componentDidMount() {
// 调用接口或者其他条件
if(...){
this.queue.enqueue(ModalA)
}
if(...){
this.queue.enqueue(ModalB)
}
if(...){
this.queue.enqueue(ModalC)
}
this.setState({
comp: this.queue.getFront()
})
}
close = () => {
this.queue.dequeue()
this.setState({
comp: this.queue.getFront()
})
}
render() {
const Modal = this.state.comp
return (
<div>
{Modal && <Modal close={this.close}/>}
</div>
)
}
}
const ModalA = (props) => {
return (
<div style={{width: 200, height: 200, background: 'red'}}>
<button onClick={props.close}>关闭</button>
</div>
)
}
const ModalB = (props) => {
return (
<div style={{width: 200, height: 200, background: 'blue'}}>
<button onClick={props.close}>关闭</button>
</div>
)
}
const ModalC = (props) => {
return (
<div style={{width: 200, height: 200, background: 'green'}}>
<button onClick={props.close}>关闭</button>
</div>
)
}
export default App;
方式二:定义好每个组件对应的name,以对象的形式推入队列,渲染时根据name去判断显示哪个组件,demo如下:
import React from 'react';
import Queue from './Queue'
class App extends React.Component {
constructor(props) {
super(props)
this.queue = new Queue()
this.state = {
front: null
}
}
componentDidMount() {
// 调用接口或者其他其他条件
if(...){
this.queue.enqueue({name: 'modalA'})
}
if(...){
this.queue.enqueue({name: 'modalB'})
}
if(...){
this.queue.enqueue({name: 'modalC'})
}
// 初始给comp赋值
this.setState({
front: this.queue.getFront()
})
}
close = () => {
this.queue.dequeue()
this.setState({
front: this.queue.getFront()
})
}
render() {
const front = this.state.front
return (
<div>
{front && front.name === 'modalA' && <ModalA close={this.close}/>}
{front && front.name === 'modalB' && <ModalB close={this.close}/>}
{front && front.name === 'modalC' && <ModalC close={this.close}/>}
</div>
)
}
}
以上就是队列的实际应用场景之一了,希望对大家有所帮助,有问题的欢迎在评论区提出,有用队列实现过其他业务功能的也可以分享出来,大家一起学习进步!!!