首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-toastify通知不会以条件形式返回

React-toastify通知不会以条件形式返回
EN

Stack Overflow用户
提问于 2020-12-06 23:51:51
回答 1查看 565关注 0票数 0

只需按一下按钮,通知就可以很轻松地工作。但是,我尝试在道具通过时激活它(true/false)。

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

然而,如果不是一个按钮,我就不能让它工作。道具通过很好,我可以console.log它。条件返回值...一些东西,但它就像一堆奇怪的字母,每次刷新它都会改变。并且不会像通知那样弹出。它只是屏幕中央的模糊字母(因为表单上方放置了{notify} )。

代码语言:javascript
复制
    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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-07 00:23:21

代码语言:javascript
复制
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函数可由组件mount和按钮访问希望我已经足够清楚了

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65170004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档