alert is assigned a value but never used warning in reactjs

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

alert is assigned a value but never used warning in reactjs

问题

在以下代码中出现警告,我想要显示消息,但它既没有显示,也没有关闭按钮。

function App() {
  const [mode, setMode] = useState('light');
  // 在下面一行获取警告
  const [alert, setAlert] = useState(null);

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

  const toggleMode = () => {
    if (mode === 'light') {
      setMode('dark');
      document.body.style.backgroundColor = '#56595b';
      showAlert("启用暗模式", "success");
    } else {
      setMode('light');
      document.body.style.backgroundColor = 'white';
      showAlert("启用亮模式", "success");
    }
  }

  return (
    <>
      <Navbar title="Blog" mode={mode} toggleMode={toggleMode} />
      <Alert alert="wtf" />
    </>
  );
}

export default App;

以下是Alert组件的内容:

import React from 'react';

export default function Alert(props) {
  return (
    <>
      {props.alert && <div className="alert alert-warning alert-dismissible fade show" role="alert">
        <strong>{props.alert.type}</strong> : {props.alert.msg}
        <button type="button" className="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>}
    </>
  )
}

警告信息:

警告 [eslint]
我想在屏幕上显示警报消息,但它没有显示
英文:

Gettting waring in following code i want to display meassage ,but neither it is showing nor dissmiss the button

function App(){
  const [mode,setMode]=useState(&#39;light&#39;);
//getting warning for below line
  const [alert,setAlert]=useState(null);

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

  const toggleMode=()=&gt;{
    if(mode===&#39;light&#39;){
      setMode(&#39;dark&#39;);
      document.body.style.backgroundColor=&#39;#56595b&#39;
      showAlert(&quot;Enable dark mode&quot;,&quot;success&quot;);
    }
    else{
      setMode(&#39;light&#39;);
      document.body.style.backgroundColor=&#39;white&#39;
      showAlert(&quot;enable light mode&quot;,&quot;success&quot;)
    }
  }


  return(
    &lt;Navbar title=&quot;Blog&quot;  mode={mode} toggleMode={toggleMode}/&gt;
    &lt;Alert alert=&quot;wtf&quot;/&gt;
    &lt;/&gt;
  );
}

export default App;    

//Below is Alert Component

import React from &#39;react&#39;

export default function Alert(props) {
  return (
    &lt;&gt;
     props.alert  &amp;&amp; &lt;div className=&quot;alert alert-warning alert- 
     dismissible fade show&quot; role=&quot;alert&quot;&gt;
     &lt;strong&gt;{props.alert.type}&lt;/strong&gt; : {props.alert.msg}
     &lt;button type=&quot;button&quot; className=&quot;close&quot; data-dismiss=&quot;alert&quot; aria- 
     label=&quot;Close&quot;&gt;
     &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
         &lt;/button&gt;
      &lt;/div&gt;
    &lt;/&gt;
  )
}

WARNING in [eslint]
I want to display alert message on screen. but it is not showing

答案1

得分: 1

这段代码的建议如下:

也许这样修改会更好:

&lt;Alert alert={alert}/&gt;

这样应该可以解决lint警告问题。

为了使空值检查起作用,你需要移除这个fragment<></>,或者将它放在{}之间。我认为直接移除这个fragment会更清晰一些:

export default function Alert(props) {
  return (
    props.alert &amp;&amp; (
      &lt;div
        className=&quot;alert alert-warning alert-dismissible fade show&quot;
        role=&quot;alert&quot;
      &gt;
        &lt;strong&gt;{props.alert.type}&lt;/strong&gt; : {props.alert.msg}
        &lt;button
          type=&quot;button&quot;
          className=&quot;close&quot;
          data-dismiss=&quot;alert&quot;
          aria-label=&quot;Close&quot;
        &gt;
          &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
        &lt;/button&gt;
      &lt;/div&gt;
    )
  )
}

正如有人提到的,"alert" 不是一个好的变量名。有一些不能使用的关键字的列表,"alert"虽然不在列表中,但有"window.alert"的全局函数,这可能会在以后引起混淆。此外,最好将状态初始化为空对象,而不是使用null,这通常被认为是一种良好的实践。例如:

const [alertMessage, setAlertMessage] = useState({msg:&quot;&quot;,type:&quot;&quot;})

这使你可以通过删除组件上的空值检查来获得更好的性能,就像这样:

export default function Alert(props: any) {
  return (
    &lt;div
      className=&quot;alert alert-warning alert-dismissible fade show&quot;
      role=&quot;alert&quot;
    &gt;
      &lt;strong&gt;{props.alert.type}&lt;/strong&gt; : {props.alert.msg}
      &lt;button
        type=&quot;button&quot;
        className=&quot;close&quot;
        data-dismiss=&quot;alert&quot;
        aria-label=&quot;Close&quot;
      &gt;
        &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
      &lt;/button&gt;
    &lt;/div&gt;
  )
}

希望对你有帮助。

英文:

Maybe this:

&lt;Alert alert=&quot;wtf&quot;/&gt;

Should be:

&lt;Alert alert={alert}/&gt;

That should fix the lint warning.

For that null check to work you need to remove that fragment <></>, or place it between {}. In my opinion it's cleaner to just remove the fragment:

export default function Alert(props) {
  return (
    props.alert &amp;&amp; (
      &lt;div
        className=&quot;alert alert-warning alert-dismissible fade show&quot;
        role=&quot;alert&quot;
      &gt;
        &lt;strong&gt;{props.alert.type}&lt;/strong&gt; : {props.alert.msg}
        &lt;button
          type=&quot;button&quot;
          className=&quot;close&quot;
          data-dismiss=&quot;alert&quot;
          aria-label=&quot;Close&quot;
        &gt;
          &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
        &lt;/button&gt;
      &lt;/div&gt;
    )
  )
}

As someone mentioned, "alert" is not a good variable name. There's a list of keywords that can't be used , alert is not on the list but there's window.alert, which can cause confusion later. Also may be a good idea to initialize your state with an empty object instead of null it's often considered a good practice. Like this for example:

const [alertMessage, setAlertMessage] = useState({msg:&quot;&quot;,type:&quot;&quot;})

This allows you to get better performance by removing the null check on your component like so:

export default function Alert(props: any) {
  return (
    &lt;div
      className=&quot;alert alert-warning alert- dismissible fade show&quot;
      role=&quot;alert&quot;
    &gt;
      &lt;strong&gt;{props.alert.type}&lt;/strong&gt; : {props.alert.msg}
      &lt;button
        type=&quot;button&quot;
        className=&quot;close&quot;
        data-dismiss=&quot;alert&quot;
        aria-label=&quot;Close&quot;
      &gt;
        &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
      &lt;/button&gt;
    &lt;/div&gt;
  )
}

Hope it helps

答案2

得分: 0

你有一些问题。

  1. 你正在使用Bootstrap模态框,但只使用了其中的一小部分。
  2. 关闭对话框需要将alertObj设置为null
  3. 你需要使用函数版本来设置mode状态。

另外,避免使用简单的变量名称,比如alertstringwindow,因为这些通常是JavaScript保留词。将你的变量命名得更具描述性,比如dialogData或类似的名称。

请查看下面的可工作示例:

const { useCallback, useState } = React;

const Navbar = ({ mode, title, toggleMode }) => {
  return (
    <header>
      <h1>{title}</h1>
      <nav>
        <ul>
          <li><a href="#home">Home</a></li>
          <li><a href="#contact">Contact</a></li>
          <li><a href="#about">About</a></li>
        </ul>
      </nav>
      <div>
        <button onClick={toggleMode}>Toggle Theme</button>
      </div>
    </header>
  );
};

const Alert = ({ alertObj, closeAlert }) =>
  alertObj != null && (
    <div className="alert alert-warning alert-dismissible fade show" role="alert">
      <strong>{alertObj.type}</strong>: {alertObj.msg}
      <button type="button" className="close" data-dismiss="alert" aria-label="Close"
          onClick={closeAlert}>
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
  );

const App = () => {
  const [mode, setMode] = useState('light');
  const [alertObj, setAlertObj] = useState(null);

  const showAlert = useCallback((message, type) => {
    setAlertObj({ msg: message, type: type });
  }, []);

  const closeAlert = useCallback(() => {
    setAlertObj(null);
  }, []);

  const toggleMode = useCallback(() => {
    setMode((currentMode) => {
      if (currentMode === 'light') {
        document.body.style.backgroundColor = '#56595b';
        showAlert("Enabled dark mode", "success");
        return 'dark';
      } else {
        document.body.style.backgroundColor = 'white';
        showAlert("Enabled light mode", "success");
        return 'light';
      }
    });
  }, [showAlert]);

  return (
    <React.Fragment>
      <Navbar title="Blog" mode={mode} toggleMode={toggleMode} />
      <Alert alertObj={alertObj} closeAlert={closeAlert} />
    </React.Fragment>
  );
};

ReactDOM
  .createRoot(document.getElementById("root"))
  .render(<App />);
header {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
header nav ul {
  display: flex;
  margin: 0;
  padding: 0;
  gap: 1rem;
  justify-content: center;
}
header nav ul li {
  display: flex;
  margin: 0;
  padding: 0.5rem;
  border: thin solid grey;
}
header div button {
  margin-top: 1rem;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-fbbOQedDUMZZ5KreZpsbe1LCZPVmfTnH7ois6mU1QK+m14rQ1l2bGBq41eYeM/fS" crossorigin="anonymous"></script>
英文:

You have a few issues.

  1. You are using Boostrap modal, but only a small piece of it
  2. Closing the dialog requires you to set the alertObj to null
  3. You need to use the function version for setting the mode state

Also, avoid simple variables names like alert, string, window, because these are typically reserved works for JavaScript. Make your variable more descriptive i.e. dialogData or something to that effect.

See the working snippet below:

<!-- begin snippet: js hide: false console: true babel: true -->

<!-- language: lang-js -->

const { useCallback, useState } = React;
const Navbar = ({ mode, title, toggleMode }) =&gt; {
return (
&lt;header&gt;
&lt;h1&gt;{title}&lt;/h1&gt;
&lt;nav&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#home&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#contact&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/nav&gt;
&lt;div&gt;
&lt;button onClick={toggleMode}&gt;Toggle Theme&lt;/button&gt;
&lt;/div&gt;
&lt;/header&gt;
);
};
const Alert = ({ alertObj, closeAlert }) =&gt;
alertObj != null &amp;&amp; (
&lt;div className=&quot;alert alert-warning alert-dismissible fade show&quot; role=&quot;alert&quot;&gt;
&lt;strong&gt;{alertObj.type}&lt;/strong&gt;: {alertObj.msg}
&lt;button type=&quot;button&quot; className=&quot;close&quot; data-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;
onClick={closeAlert}&gt;
&lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
&lt;/button&gt;
&lt;/div&gt;
);
const App = () =&gt; {
const [mode, setMode] = useState(&#39;light&#39;);
const [alertObj, setAlertObj] = useState(null);
const showAlert = useCallback((message, type) =&gt; {
setAlertObj({ msg : message, type : type })
}, []);
const closeAlert = useCallback((message, type) =&gt; {
setAlertObj(null);
}, []);
const toggleMode = useCallback(() =&gt; {
setMode(currentMode =&gt; {
if (currentMode === &#39;light&#39;) {
document.body.style.backgroundColor = &#39;#56595b&#39;;
showAlert(&quot;Enabled dark mode&quot;, &quot;success&quot;);
return &#39;dark&#39;;
} else {
document.body.style.backgroundColor = &#39;white&#39;;
showAlert(&quot;Enabled light mode&quot;, &quot;success&quot;);
return &#39;light&#39;;
}
});
}, []);
return (
&lt;React.Fragment&gt;
&lt;Navbar title=&quot;Blog&quot; mode={mode} toggleMode={toggleMode} /&gt;
&lt;Alert alertObj={alertObj} closeAlert={closeAlert} /&gt;
&lt;/React.Fragment&gt;
);
};
ReactDOM
.createRoot(document.getElementById(&quot;root&quot;))
.render(&lt;App /&gt;);

<!-- language: lang-css -->

header { display: flex; flex-direction: column; justify-content: center; align-items: center; }
header nav ul { display: flex; margin: 0; padding: 0; gap: 1rem; justify-content: center; }
header nav ul li { display: flex; margin: 0; padding: 0.5rem; border: thin solid grey; }
header div button { margin-top: 1rem; }

<!-- language: lang-html -->

&lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM&quot; crossorigin=&quot;anonymous&quot;&gt;
&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js&quot; integrity=&quot;sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js&quot; integrity=&quot;sha384-fbbOQedDUMZZ5KreZpsbe1LCZPVmfTnH7ois6mU1QK+m14rQ1l2bGBq41eYeM/fS&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月13日 16:37:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677430.html
匿名

发表评论

匿名网友

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

确定