React应用中的消息订阅发布模式实践:PubSub库的应用

React应用中的消息订阅发布模式实践:PubSub库的应用

随着React应用的复杂性增加,组件之间的通信变得越来越重要。而消息订阅发布(PubSub)模式提供了一种简洁而灵活的方式来实现组件间的解耦通信。在这篇博客中,我们将探讨如何在React应用中使用PubSub库来实现消息订阅发布模式,以实现组件间的通信。

什么是消息订阅发布模式?

消息订阅发布模式是一种软件设计模式,用于实现组件之间的松耦合通信。在这种模式中,有一个中心化的消息通信系统,组件可以通过订阅和发布消息来进行通信,而不需要直接引用彼此。

在React中使用PubSub库

首先,我们需要安装PubSub库:

bash 复制代码
npm install pubsub-js

然后,让我们来看一个示例,展示如何在React应用中使用PubSub进行组件间的通信。

发布消息的组件(Search)

jsx 复制代码
// Search.jsx
import React, { Component } from 'react';
import PubSub from 'pubsub-js';

export default class Search extends Component {
  state = {
    keyword: '',
  }

  onChange = (e) => {
    this.setState({ keyword: e.target.value });
  }

  onSearch = () => {
    const { keyword } = this.state;
    PubSub.publish('searchKeywordChanged', keyword);
  }

  onKeyPress = (e) => {
    if (e.key === 'Enter') {
      this.onSearch();
    }
  }

  render() {
    return (
      <div className="input-group mb-3">
        <input
          type="text"
          className="form-control"
          placeholder="输入关键字"
          aria-label="Recipient's username"
          aria-describedby="basic-addon2"
          onChange={this.onChange}
          onKeyPress={this.onKeyPress}
        />
        <div className="input-group-append">
          <button
            className="btn btn-outline-secondary"
            type="button"
            onClick={this.onSearch}
          >
            搜索
          </button>
        </div>
      </div>
    )
  }
}

Search组件中,当用户输入关键字并按下回车或点击搜索按钮时,我们使用PubSub库的publish方法发布了一个名为searchKeywordChanged的主题,并传递了当前关键字作为参数。

订阅消息的组件(Users)

jsx 复制代码
// Users.jsx
import React, { Component } from 'react';
import axios from 'axios';
import PubSub from 'pubsub-js';

import User from '../User';

export default class Users extends Component {
  token = null

  state = {
    users: [],
  }

  componentDidMount() {
    // 默认先获取一次用户
    this.fetchUsers();
    this.token = PubSub.subscribe('searchKeywordChanged', (_, keyword) => {
      this.fetchUsers(keyword);
    });
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.token);
  }

  fetchUsers = async (keyword) => {
    const res = await axios.get(`/api/github/search/users?q=${keyword || 'h'}`);
    if (res && res.data) {
      this.setState({ users: res.data.items || [] });
    }
  }

  render() {
    const { users } = this.state;
    return (
      <div className="row row-cols-4 g-4">
        {users.map(user => <User key={user.node_id} user={user} />)}
      </div>
    )
  }
}

Users组件中,我们使用PubSub库的subscribe方法订阅了名为searchKeywordChanged的主题。当这个主题的消息被发布时,我们会触发回调函数,重新获取相应的用户信息并更新UI。

通过这种消息订阅发布的模式,我们可以实现组件之间的解耦,使得它们能够独立地进行通信,而不需要直接引用彼此。这样的设计模式有助于提高代码的可维护性和可扩展性,使得应用程序更易于理解和维护。

参考

相关推荐
清羽_ls7 小时前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
mapbar_front13 小时前
react项目开发—关于代码架构/规范探讨
前端·react.js
需要兼职养活自己13 小时前
react高阶组件
前端·react.js
今天周二14 小时前
vite 将react老项目中的没有兼容处理的写法转成兼容性写法
react.js
GISBox14 小时前
GISBox如何让GeoTIFF突破Imagery Provider加载限制?
react.js·json·gis
天蓝色的鱼鱼16 小时前
Next.js 渲染模式全解析:如何正确选择客户端与服务端渲染
前端·react.js·next.js
果粒chenl19 小时前
React学习(四) --- Redux
javascript·学习·react.js
LRH20 小时前
React 双缓存架构与 diff 算法优化
前端·react.js
中微子21 小时前
别再被闭包坑了!React 19.2 官方新方案 useEffectEvent,不懂你就 OUT!
前端·javascript·react.js
1in21 小时前
一文解析UseState的的执行流程
前端·javascript·react.js