一、生成唯一id
库名:Nano ID
地址:https://www.npmjs.com/package/nanoid
1.安装组件库
代码如下(示例):
npm i nanoid
2.使用例子
代码如下(示例):
import { nanoid } from 'nanoid' //引入插件
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"。生成唯一id
二、发布/订阅消息
库名:pubsub-js
地址:https://www.npmjs.com/package/pubsub-js
1.安装组件库
代码如下(示例):
npm i pubsub-js
2.使用例子
代码如下(示例):
- 发送消息
import React, { Component } from "react";
import PubSub from "pubsub-js";
export default class ClassOne extends Component {
state = {
value: "",
};
handleInput = (e) => {
this.setState({
value: e.target.value,
});
};
Publish = () => {
PubSub.publish("MYTOPIC", this.state.value);
};
render() {
return (
<dicv>
<input type="text" onChange={this.handleInput} />
<button style={{ marginLeft: "8px" }} onClick={this.Publish}>
发送消息
</button>
</dicv>
);
}
}
- 订阅消息
import React, { Component } from "react";
import PubSub from "pubsub-js"; //引入插件
export default class ClassTwo extends Component {
state = {
message: "",
};
componentDidMount() {
//接受不了订阅消息,并获取到消息发送的data
this.token = PubSub.subscribe("MYTOPIC", (_, message) => {
this.setState({
message,
});
});
}
componentWillUnmount() {
PubSub.unsubscribe(this.token); //组建将要卸载时,取消订阅消息
}
render() {
const { message } = this.state;
return (
<div>
<h2>收到的消息:{message}</h2>
</div>
);
}
}