如何更改数组中的布尔值?
Posted
技术标签:
【中文标题】如何更改数组中的布尔值?【英文标题】:How to change bool in an array? 【发布时间】:2020-05-14 21:12:53 【问题描述】:如何访问数组中的特定元素并将其值更改为相反的值?为了不重复代码,我想让模态窗口这样显示
const [visiblePopup, setVisiblePopup] = useState([
modalUsers: false,
modalDetails: false,
modalWarning: false,
modalUpdate: false
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
【问题讨论】:
可能重复:***.com/questions/11604409/how-to-toggle-a-boolean 【参考方案1】:你可以试试这样的:
setVisiblePopup([...visiblePopup, modalUsers: true])
【讨论】:
【参考方案2】:使用对象和创建函数来切换您的状态,而不是使用数组。
const [visiblePopup, setVisiblePopup] = useState(
modalUsers: false,
modalDetails: false,
modalWarning: false,
modalUpdate: false
);
togglePopup = name => setVisiblePopup(prevVisiblePopup => (
...visiblePopup,
[name]: !prevVisiblePopup[name]
)
togglePopup('modalUpdate'); // to toggle modalUpdate
【讨论】:
【参考方案3】:您可以使用单独的函数来处理这些模式切换中的每一个:
const [visiblePopup, setVisiblePopup] = useState(
modalUsers: false,
modalDetails: false,
modalWarning: false,
modalUpdate: false
);
toggleModalUsers = () => setVisiblePopup(prevState => (
...visiblePopup,
modalUsers: !modalUsers
)
toggleModalDetails = () => setVisiblePopup(prevState => (
...visiblePopup,
modalDetails: !modalDetails
)
toggleModalWarning = () => setVisiblePopup(prevState => (
...visiblePopup,
modalWarning: !modalWarning
)
toggleModalUpdate = () => setVisiblePopup(prevState => (
...visiblePopup,
modalUpdate: !modalUpdate
)
【讨论】:
以上是关于如何更改数组中的布尔值?的主要内容,如果未能解决你的问题,请参考以下文章