英文:
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">×</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('light');
//getting warning for below line
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("Enable dark mode","success");
}
else{
setMode('light');
document.body.style.backgroundColor='white'
showAlert("enable light mode","success")
}
}
return(
<Navbar title="Blog" mode={mode} toggleMode={toggleMode}/>
<Alert alert="wtf"/>
</>
);
}
export default App;
//Below is Alert Component
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>
</>
)
}
WARNING in [eslint]
I want to display alert message on screen. but it is not showing
答案1
得分: 1
这段代码的建议如下:
也许这样修改会更好:
<Alert alert={alert}/>
这样应该可以解决lint警告问题。
为了使空值检查起作用,你需要移除这个fragment<></>,或者将它放在{}之间。我认为直接移除这个fragment会更清晰一些:
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>
)
)
}
正如有人提到的,"alert" 不是一个好的变量名。有一些不能使用的关键字的列表,"alert"虽然不在列表中,但有"window.alert"的全局函数,这可能会在以后引起混淆。此外,最好将状态初始化为空对象,而不是使用null
,这通常被认为是一种良好的实践。例如:
const [alertMessage, setAlertMessage] = useState({msg:"",type:""})
这使你可以通过删除组件上的空值检查来获得更好的性能,就像这样:
export default function Alert(props: any) {
return (
<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>
)
}
希望对你有帮助。
英文:
Maybe this:
<Alert alert="wtf"/>
Should be:
<Alert alert={alert}/>
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 && (
<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>
)
)
}
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:"",type:""})
This allows you to get better performance by removing the null check on your component like so:
export default function Alert(props: any) {
return (
<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>
)
}
Hope it helps
答案2
得分: 0
你有一些问题。
- 你正在使用Bootstrap模态框,但只使用了其中的一小部分。
- 关闭对话框需要将
alertObj
设置为null
。 - 你需要使用函数版本来设置
mode
状态。
另外,避免使用简单的变量名称,比如alert
,string
,window
,因为这些通常是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">×</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.
- You are using Boostrap modal, but only a small piece of it
- Closing the dialog requires you to set the
alertObj
tonull
- 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 }) => {
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((message, type) => {
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';
}
});
}, []);
return (
<React.Fragment>
<Navbar title="Blog" mode={mode} toggleMode={toggleMode} />
<Alert alertObj={alertObj} closeAlert={closeAlert} />
</React.Fragment>
);
};
ReactDOM
.createRoot(document.getElementById("root"))
.render(<App />);
<!-- 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 -->
<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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论