“Cannot read properties of undefined (reading ‘toLowerCase’)” 如何解决这个错误?

huangapple go评论109阅读模式
英文:

How to resolve the following error? "Cannot read properties of undefined (reading 'toLowerCase')

问题

I am making a project on React and have come across an error which I have given below.

我正在进行一个React项目,遇到了下面的错误。

I am trying to resolve the error but am unable to do so.

我正在尝试解决这个错误,但无法成功。

Can someone please help?

请问有人能帮忙吗?

The error is as follows:
Cannot read properties of undefined (reading 'toLowerCase')
TypeError: Cannot read properties of undefined (reading 'toLowerCase')

错误如下:
无法读取未定义的属性(读取 'toLowerCase')
TypeError: 无法读取未定义的属性(读取 'toLowerCase')

App.js

import "./App.css";
import Navbar from "./Components/Navbar";
import TextForm from "./TextForm";
import React, { useState } from "react";
import Alert from "./Components/Alert";

function App() {
  const [mode, setMode] = useState("light");
  const [alert, setAlert] = useState(null);

  const showAlert = (message, type) => {
    setAlert({
      msg: message,
      type: type,
    });
    setTimeout(() => {
      showAlert(null);
    }, 1000);
  };

  const toggleMode = () => {
    if (mode === "light") {
      setMode("dark");
      document.body.style.backgroundColor = "black";
      showAlert("The dark mode has been set", "success");
    } else {
      setMode("light");
      document.body.style.backgroundColor = "white";
      showAlert("The light mode has been set", "success");
    }
  };
  return (
    <>
      <Navbar toggleMode={toggleMode} mode={mode} />
      <Alert alert={alert} />
      <TextForm
        heading="This is textarea"
        mode={mode}
        alert={alert}
        showAlert={showAlert}
      />
    </>
  );
}

export default App;

Alert.js

import React from "react";

export default function Alert(props) {
  const capitalize = (word) => {
    const lower = word.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };
  return (
    props.alert &&
    (
      <div
        class={`alert alert-${props.alert.type} alert-dismissible fade show`}
        role="alert"
      >
        <strong>{capitalize(props.alert.type)}:</strong>{props.alert.msg}
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="alert"
          aria-label="Close"
        ></button>
      </div>
    )
  );
}

Alert.js 文件内容已提供。

英文:

I am making a project on React and have come across an error which I have given below.

I am trying to resolve the error but am unable to do so.

Can someone please help?
The error is as follows:
Cannot read properties of undefined (reading 'toLowerCase')
TypeError: Cannot read properties of undefined (reading 'toLowerCase')

App.js

import &quot;./App.css&quot;;
import Navbar from &quot;./Components/Navbar&quot;;
import TextForm from &quot;./TextForm&quot;;
import React, { useState } from &quot;react&quot;;
import Alert from &quot;./Components/Alert&quot;;

function App() {
  const [mode, setMode] = useState(&quot;light&quot;);
  const [alert, setAlert] = useState(null);

  const showAlert = (message, type) =&gt; {
    setAlert({
      msg: message,
      type: type,
    });
    setTimeout(() =&gt; {
      showAlert(null);
    }, 1000);
  };

  const toggleMode = () =&gt; {
    if (mode === &quot;light&quot;) {
      setMode(&quot;dark&quot;);
      document.body.style.backgroundColor = &quot;black&quot;;
      showAlert(&quot;The dark mode has been set&quot;, &quot;success&quot;);
    } else {
      setMode(&quot;light&quot;);
      document.body.style.backgroundColor = &quot;white&quot;;
      showAlert(&quot;The light mode has been set&quot;, &quot;success&quot;);
    }
  };
  return (
    &lt;&gt;
      &lt;Navbar toggleMode={toggleMode} mode={mode} /&gt;
      &lt;Alert alert={alert} /&gt;
      &lt;TextForm
        heading=&quot;This is textarea&quot;
        mode={mode}
        alert={alert}
        showAlert={showAlert}
      /&gt;
    &lt;/&gt;
  );
}

export default App;

Alert.js

import React from &quot;react&quot;;

export default function Alert(props) {
  const capitalize = (word) =&gt; {
    const lower = word.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };
  return (
    props.alert &amp;&amp; (
      &lt;div
        class={`alert alert-${props.alert.type} alert-dismissible fade show`}
        role=&quot;alert&quot;
      &gt;
        &lt;strong&gt;{capitalize(props.alert.type)}&lt;/strong&gt;:{props.alert.msg}
        &lt;button
          type=&quot;button&quot;
          class=&quot;btn-close&quot;
          data-bs-dismiss=&quot;alert&quot;
          aria-label=&quot;Close&quot;
        &gt;&lt;/button&gt;
      &lt;/div&gt;
    )
  );
}

答案1

得分: 0

以下是翻译好的部分:

TL;DR

你可能想要在 setTimeout 函数中使用 setAlert,而不是调用 showAlert(后者还会导致无限循环):

const showAlert = (message, type) => {
  setAlert({
    msg: message,
    type: type,
  });
  setTimeout(() => {
    setAlert(null);
  }, 1000);
}

const showAlert = (message, type) => {
  setAlert({
    msg: message,
    type: type,
  });
  setTimeout(() => {
    showAlert(null);
  }, 1000);
}

当调用 showAlert(null) 时,它解析为 setAlert({ msg: null, type: undefined })

alert 本身不为空: { msg: null, type: undefined },这使得 props.alert 为真,但 props.alert.typeundefined,因此 capitalize(props.alert.type) 收到一个 undefined

英文:

TL;DR

What you might want is to setAlert instead of calling showAlert (which also causes an infinite loop) in the setTimeout function:

const showAlert = (message, type) =&gt; {
  setAlert({
    msg: message,
    type: type,
  });
  setTimeout(() =&gt; {
//  showAlert(null); // wrong
    setAlert(null);
  }, 1000);
}

const showAlert = (message, type) =&gt; {
  setAlert({
    msg: message,
    type: type,
  });
  setTimeout(() =&gt; {
    showAlert(null);
//  ^^^^^^^^^^^^^^^
  }, 1000);
}

When showAlert(null) is called, it resolves into setAlert({ msg: null, type: undefined }).

The alert itself is not not empty: { msg: null, type: undefined }, which makes props.alert truthy, but props.alert.type is undefined, so capitalize(props.alert.type) receives an undefined.

答案2

得分: 0

错误的原因是因为在capitalize函数中,你应该检查单词是否未定义或为空,然后执行进一步的操作,而在你的情况下,操作是.toLowerCase()

英文:

Error cause is because the in the capitalize function you should check if word is not undefined or null then you should perform further operations, in your case operation is .toLowerCase()

答案3

得分: 0

使用 "showAlert(null)" 调用时,警报对象在技术上并不是空的,因为它具有值为 null 的 "msg" 属性,它的 "type" 属性是未定义的。这意味着 props.alert 是真值,props.alert.type 是未定义的,因此您会收到此错误。

英文:

With "showAlert(null)" call, the alert object is not technically empty as it has a "msg" property with a value of null, its "type" property is undefined.

That means props.alert is truthy, props.alert.type is undefined, hence you are getting this error.

huangapple
  • 本文由 发表于 2023年3月23日 12:38:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75819299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定