反应呈现的意外数字

时间:2018-10-27 08:39:21

标签: javascript reactjs

我有以下React示例,每当isShowing状态为true时,我都试图显示成功的吐司(来自mdbootstrap库)。对于烤面包,这可以按预期工作,但是按钮旁边会显示一个数字,每次单击后都会递增。该数字还会显示为App文件中主div的子代(请参见附件的图像和codeandbox链接)。 预先感谢!

import React, { Component } from "react";
import Nav from "./Navbar";
import Routes from "./Routes";
import Mes from "./Message";
import { Button, toast } from "mdbreact";
import "./App.css";

class App extends Component {
  state = {
    isShowing: false
  };

  handleClick = () => {
    this.setState({
      isShowing: true
    });
  };

  render() {
    return (
      <div className="App">
        <Mes />
        <Button color="primary" onClick={this.handleClick}>
          show Alert{" "}
        </Button>
        {this.state.isShowing ? toast.success("Success message") : ""}
        <Routes />
      </div>
    );
  }
}

export default App;

codesandbox链接:https://codesandbox.io/s/l2xqplx4rm

enter image description here

1 个答案:

答案 0 :(得分:2)

您无需在代码中呈现toast.success。删除

{this.state.isShowing ? toast.success("Success message") : ""}

在以上代码情况下,您绑定烤面包的toast.success方法的响应只是激活的烤面包长度。所以它的显示号在那里。

下面的代码足以在单击按钮时显示吐司。

import React, { Component } from "react";
import Nav from "./Navbar";
import Routes from "./Routes";
import Mes from "./Message";
import { Button, toast } from "mdbreact";
import "./App.css";

class App extends Component {

  handleClick = () => {
     //show toast
     toast.success("Success message");
  };

  render() {
    return (
      <div className="App">
        <Mes />
        <Button color="primary" onClick={this.handleClick}>
          Show Alert
        </Button>
        <Routes />
      </div>
    );
  }
}

export default App;

此处已更新code