React-toastify 通知不会 return 有条件

React-toastify notification won't return in conditional

使用按钮即可轻松完成通知。但是,我试图在道具通过时激活它 (true/false)。

基本上,用户点击这个选项卡,如果他们没有登录,它会弹出通知,告诉他们登录。

但是,如果没有按钮,我无法让它工作。道具通过就好了,我可以console.log。还有条件 returns... 东西,但它就像一堆奇怪的字母,每次刷新都会改变。并且不会像通知那样弹出。它只是屏幕中间的模糊字母(因为 {notify} 放在表格上方)。

    import React, {Component} from 'react';
    import { ToastContainer, toast } from 'react-toastify';
    import 'react-toastify/dist/ReactToastify.css';

    class Alerts extends Component {
      constructor(props){
        super(props)
        this.state = { 
          alertLogin: ''
        }
      }

      render() {

        const notify = () => toast("Please login before adding a recipe!");

        // tried to make a conditional to check if prop alertLogin is true or false
        // then calls notify function if false 
        if (!this.props.alertLogin) {
          console.log('alert props received', this.props.alertLogin)
          return notify()
        }

        return ( 
        <div>
          {/* <button onClick={notify}>Notify !</button> */}
          {notify}
          <ToastContainer />
        </div>
        );
      }
    }
    
    export default Alerts;
import React, { Component } from "react";
import "./styles.css";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
class Alerts extends Component {
  constructor(props){
    super(props)
    this.state = { 
      alertLogin: ''
    }
  }
  componentDidMount() {
    // tried to make a conditional to check if prop alertLogin is true or false
    // then calls notify function if false
    if (!this.props.alertLogin) {
      console.log("alert props received", this.props.alertLogin);
      this.notify();
    }
  }
  notify = () => toast("Please login before adding a recipe!");
  render() {
    return (
      <div>
        <button onClick={(e) => this.notify()}>Notify !</button>
        <ToastContainer />
      </div>
    );
  }
}
export default Alerts;

Codepen for the solution

首先你把函数中的if语句放到componentDidMount中 因为我猜是阻止渲染元素本身渲染 第二,通过在渲染函数之前声明它来使组件访问 toast 函数确实挂载和按钮希望我足够清楚