React消息订阅与发布机制

1. 安装并引入模块

npm install pubsub-js
import PubSub from 'pubsub-js';
// or when using CommonJS
const PubSub = require('pubsub-js');

2. 基本使用

  1. 先订阅,再发布
  2. 适用于任意组件间通信
  3. 要在组件的componentWillUnmount中取消订阅
// 创建订阅的回调函数
var mySubscriber = function (msg, data) {
    console.log(msg, data);
};

// 订阅
var token = PubSub.subscribe('MY TOPIC', mySubscriber);

// 发布
PubSub.publish('MY TOPIC', 'hello world!');

// 取消指定订阅
PubSub.unsubscribe(token);
// 取消一个函数的所有订阅
PubSub.unsubscribe(mySubscriber);

3. 基本案例

React不同组件之间的通信。

1. 发布消息的组件

import PubSub from 'pubsub-js';

...
PubSub.publish('msg', { isFirst: false, isLoading: true });
...

2. 订阅消息的组件

import PubSub from 'pubsub-js';

...
componentDidMount() {
    // 直接将回调函数写在一起
    // 不需要回调函数的第一个参数,用_占位
    this.token = PubSub.subscribe('msg', (_, stateObj) => {
        this.setState(stateObj);
    });
}

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

参考链接:pubsub-js

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
React中,可以使用Context API和Redux库来实现消息订阅模式传值。 1. 使用Context API Context API是React提供的一种跨级组件传递数据的方式,可以让我们在组件树中不必一级一级地传递props,而是直接在需要的组件中订阅数据。示例代码如下: ```jsx import React, { createContext, useContext, useState } from 'react'; const AppContext = createContext(); function App() { const [count, setCount] = useState(0); return ( <AppContext.Provider value={{ count, setCount }}> <div> <Counter /> </div> </AppContext.Provider> ); } function Counter() { const { count, setCount } = useContext(AppContext); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } ``` 在上面的示例中,我们在App组件中创建了一个AppContext上下文,并将count和setCount作为value传递给了Provider组件。在Counter组件中,我们使用useContext钩子来订阅了这个上下文,并直接使用了count和setCount。 2. 使用Redux库 Redux是一个专门用于管理应用状态的库,它实现了消息订阅模式,并提供了一些API来让我们在组件中订阅和修改状态。示例代码如下: ```jsx import { createStore } from 'redux'; import { Provider, useSelector, useDispatch } from 'react-redux'; // 定义action类型和action creator const INCREMENT = 'INCREMENT'; const DECREMENT = 'DECREMENT'; function increment() { return { type: INCREMENT }; } function decrement() { return { type: DECREMENT }; } // 定义reducer function counterReducer(state = { count: 0 }, action) { switch (action.type) { case INCREMENT: return { count: state.count + 1 }; case DECREMENT: return { count: state.count - 1 }; default: return state; } } // 创建store const store = createStore(counterReducer); function App() { return ( <Provider store={store}> <div> <Counter /> </div> </Provider> ); } function Counter() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); } ``` 在上面的示例中,我们先定义了两个action类型和对应的action creator,然后定义了一个reducer来处理这些action。接着,我们创建了一个store,并将reducer传递给了createStore方法来生成store。在Counter组件中,我们使用useSelector钩子来订阅了store中的count状态,并使用useDispatch来获取dispatch函数来触发action。这样,当我们点击Increment或Decrement按钮时,就会通过dispatch方法触发对应的action,从而修改count状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火星飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值