Javascript 当道具检查为true时,如何使用react toastify inside类组件显示toast
我正在从事react项目,当props(isNotificationOpen)为true时,我试图在div部分中使用react toastify显示toast。我尝试了一个类似于贝娄的例子,但我不希望在按下按钮时触发toast,我希望在isNotificationOpen props设置为true时触发tost,我如何实现这一点Javascript 当道具检查为true时,如何使用react toastify inside类组件显示toast,javascript,reactjs,react-toastify,Javascript,Reactjs,React Toastify,我正在从事react项目,当props(isNotificationOpen)为true时,我试图在div部分中使用react toastify显示toast。我尝试了一个类似于贝娄的例子,但我不希望在按下按钮时触发toast,我希望在isNotificationOpen props设置为true时触发tost,我如何实现这一点 const notify = () => toast("Wow so easy !"); render() { return (
const notify = () => toast("Wow so easy !");
render() {
return (
<div className="d-flex" style={{ margin: "25px" }}>
<div className="mr-auto p-2">
{this.props.isNotificationOpen ? (
<div>
<div>
<button onClick={notify}>Notify !</button>
<ToastContainer />
</div>
//Show toast here...
</div>
) : (
<p />
)} ```
constnotify=()=>toast(“哇,太简单了!”);
render(){
返回(
{this.props.isNotificationOpen(
通知
//在这里举杯。。。
) : (
)} ```
使用组件生命周期功能响应isNotificationOpen
道具更改以触发通知
基于类的组件示例
notify = () => toast('Wow so easy!');
componentDidMount() {
const { isNotificationOpen } = this.props;
isNotificationOpen && this.notify();
}
componentDidUpdate(prevProps) {
const { isNotificationOpen } = this.props;
if (prevProps.isNotificationOpen !== isNotificationOpen) {
isNotificationOpen && this.notify();
}
}
useEffect(() => {
props.isNotificationOpen && toast('Wow so easy!');
}, [props.isNotificationOpen]);
功能组件示例
notify = () => toast('Wow so easy!');
componentDidMount() {
const { isNotificationOpen } = this.props;
isNotificationOpen && this.notify();
}
componentDidUpdate(prevProps) {
const { isNotificationOpen } = this.props;
if (prevProps.isNotificationOpen !== isNotificationOpen) {
isNotificationOpen && this.notify();
}
}
useEffect(() => {
props.isNotificationOpen && toast('Wow so easy!');
}, [props.isNotificationOpen]);
Thansks对于答案,我正在使用components类,我只是在render()中添加了这段代码,后来我在上面添加了一个函数,它起作用了:)
{this.notify()}如果我的答案有助于解决你的问题,那么请考虑将它标记为接受。不过,我想提醒你,不要在代码< >渲染/<代码>函数中发出副作用,因为Read可以在“渲染”期间多次调用<代码>渲染< /代码>函数。在每个渲染周期运行一次componentDidMount
或ComponendDipDate
生命周期之前的阶段。调用this.notify()render
中的
可能会意外地触发多个祝酒词。您在我的下一期文章中发现了该警告,并且完全正确,该警告现在对我来说确实是一个问题,因为我正在根据(setTimeout)将prop值设置为false秒我的吐司被多次显示,我目前正在处理componentDidMount
和componenddipdate
,修复此问题,谢谢