【问题标题】:ReactJS - Function Based Component Rendering Multiple TimesReactJS - 基于函数的组件多次渲染
【发布时间】:2021-03-08 06:19:19
【问题描述】:

由于某些原因,我的组件多次渲染。我在here找到了相关文章。它说它是正常的,实际上是用于调试目的的反应特性。但是,由于多次渲染,Home.js 中的scrollNotification 函数会多次显示通知。

我试过这样称呼它{() => scrollNotifications()} 和这个{scrollNotifications}。他们都没有工作。

你能帮我解决这个问题吗?谢谢!

Github 链接:https://github.com/alrafiabdullah/Voting-Instructions

App.js

import React, { useState, useEffect } from "react";
import { WiDaySunny, WiMoonWaxingCrescent5 } from "react-icons/wi";

import Home from "./components/home/Home";
import Title from "./components/Title/Title";

import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import "popper.js";

function App() {
  const [darkMode, setDarkMode] = useState(getInitialMode());
  const [isNotMobile, setIsNotMobile] = useState(false);

  useEffect(() => {
    localStorage.setItem("dark", JSON.stringify(darkMode));
  }, [darkMode]);

  useEffect(() => {
    const width = window.innerWidth;
    console.log(width);
    if (width > 768) {
      setIsNotMobile(true);
    }
  }, [isNotMobile]);

  function getInitialMode() {
    const isReturningUser = "dark" in localStorage;
    const savedMode = JSON.parse(localStorage.getItem("dark"));
    const userPreferDark = getPrefColorScheme();

    if (isReturningUser) {
      return savedMode;
    } else if (userPreferDark) {
      return true;
    } else {
      return false;
    }
  }

  function getPrefColorScheme() {
    if (!window.matchMedia) return;
    return window.matchMedia("prefers-color-scheme: dark").matches;
  }

  return (
    <React.Fragment>
      <div className={darkMode ? "dark-mode" : "light-mode"}>
        {isNotMobile && (
          <>
            <span
              align="center"
              onClick={() => setDarkMode((prevMode) => !prevMode)}
            >
              {darkMode ? (
                <>
                  <WiDaySunny size={40} style={{ color: "#f7f7f7" }} />
                  <span>Light</span>
                </>
              ) : (
                <>
                  <WiMoonWaxingCrescent5
                    size={40}
                    style={{ color: "#006790" }}
                  />
                  <span>Dark</span>
                </>
              )}
            </span>
            <Title />
          </>
        )}

        <Home />
      </div>
    </React.Fragment>
  );
}

export default App;

Home.js

import React from "react";
import $ from "jquery";
import ReactNotification, { store } from "react-notifications-component";
import Card from "./Card/Card";

import "react-notifications-component/dist/theme.css";

function Home() {
  console.log("Home");
  function scrollNotification() {
    console.log("Notification");
    $(window).on("load", () => {
      store.addNotification({
        title: "Notification from ACM Vote!",
        message:
          "This website is still in progress.\nThank you for visiting!!! ????",
        type: "info",
        container: "top-right",
        insert: "top",
        animationIn: ["animated", "fadeIn"],
        animationOut: ["animated", "fadeOut"],

        dismiss: {
          duration: 5000,
          onScreen: true,
          showIcon: true,
        },
      });
    });
  }

  return (
    <div onLoad={scrollNotification()} className="mt-5">
      <ReactNotification />
      <div>
        <h3 className="container">Voting Rules of the Fall 2020 Election</h3>
      </div>
      <div>
        <Card />
      </div>
    </div>
  );
}

export default Home;

【问题讨论】:

    标签: javascript reactjs frontend react-component


    【解决方案1】:

    这是因为 useEffect 你正在更新 isNotMobile 的状态,并且你也在寻找状态的变化

    useEffect(() => {
        const width = window.innerWidth;
        console.log(width);
        if (width > 768) {
          setIsNotMobile(true);
        }
      }, [isNotMobile]);
    

    也许你可以尝试在width的基础上更新状态

    【讨论】:

    • 所以,我用类组件重构了它,它现在可以工作了!
    • 很高兴听到这个消息 :)
    猜你喜欢
    • 1970-01-01
    • 2017-11-06
    • 2018-11-02
    • 1970-01-01
    • 2016-12-02
    • 2020-10-16
    • 2019-03-30
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多