不使用redux重新渲染组件

问题描述 投票:1回答:1

当我看到这个库时:

https://github.com/fkhadra/react-toastify

他们不使用redux。但他们可以称之为

toast("Wow so easy !");

显示吐司组件。

所以无论如何还是关键是我没有redux就能实现这一点。

reactjs state
1个回答
1
投票

实现这一目标的最简单方法是将组件安装在另一个div上。为此,在你的index.html中加上一个div就像这样

<div id="toastDiv"></div>

现在你可以制作你的吐司组件了

import React from "react";
let message = ""; // global variable we change when the user calls our function

// this function will change the global variable, and reset it after 5 secs
export function showMessage(userMessage) {
  message = userMessage;
  console.log("calling ...");
  setTimeout(() => {
    message = "";
  }, 5000);
}

// our component
export class Toast extends React.Component {
  constructor() {
    super();
    this.state = {
      show: false,
      message
    };
  }
  // we continuously check for change in our global variable after our component has mounted and then set our states accordingly
  componentDidMount() {
    setInterval(() => {
      this.setState({
        show: message !== "",
        message
      });
    }, 10);
  }

  // in the render we check if our states tell us to show or not the toast, and render the toast accordingly
  render() {
    return (
      <div>
        {this.state.show && (
          <div style={{ position: "fixed", right: 10, top: 10, opacity: 100, background: 'steelblue' }}>
            {this.state.message}
          </div>
        )}
      </div>
    );
  }
}

在你的root应用程序中,你必须将这个toast安装到你的toastDiv

import React from "react";
import ReactDOM from "react-dom";
import { Toast, showMessage } from "./toast";

import "./styles.css";

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <button
          onClick={() => {
            // -------------- we show our message from here ------
            showMessage("message");
            // -------------- we show our message from here ------
          }}
        >
          Show message
        </button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

// this is where we are mounting our toast
const toastDivElement = document.getElementById("toastDiv");
ReactDOM.render(<Toast />, toastDivElement);

在这里找到工作代码沙箱https://codesandbox.io/s/2x5k05wny

© www.soinside.com 2019 - 2024. All rights reserved.