javascript - React useState 导致 if-else 无法正常工作
问题描述
所以我试图在条件语句中使用useState
钩子(React JS)设置一个值。if-else
我需要检查数组addOnName
中是否有(作为参数传递),addOnContainer
如果有,我需要将addOnPrice
(也作为参数传递)减去totalprice
使用setTotalPrice
(useState
钩子)。
如果addOnContainer
不包括addOnName
,我必须将 添加addOnPrice
到totalprice
。
该代码工作正常,因为它在 chrome 控制台中为我提供了正确的输出。但是当我尝试使用useState
钩子设置总价时,只有 if 块运行,并且else
无论条件如何,都不会运行。
我曾尝试将useState
移出,if-else
但没有运气。
我在这里做错了什么?请注意,此功能设置为在单击复选框时执行。
const [totalPrice, setTotalPrice] = useState(200)
function selectAddOn(addOnName, addOnPrice) {
let temp = totalPrice
if (!addOnContainer.includes(addOnName)) {
temp = totalPrice + addOnPrice
setTotalPrice(temp)
} else {
//never reaches even if the condition is false when useState is used.
temp = totalPrice - addOnPrice
setTotalPrice(temp)
}
}
解决方案
在每次重新渲染时,let addOnContainer = [];
都会重置为空数组。
您可以使用 auseRef
来避免它:
const {useState, useRef} = React
function App() {
const [totalPrice, setTotalPrice] = useState(200);
const addOnContainer = useRef([]);
// let addOnContainer = []; // This was the ISSUE
function addToTotalPrice (addOnName, addOnPrice) {
let temp = totalPrice;
if(!addOnContainer.current.includes(addOnName)){
addOnContainer.current.push(addOnName);
temp = totalPrice + addOnPrice;
setTotalPrice(temp)
} else {
temp = totalPrice - addOnPrice;
setTotalPrice(temp);
}
}
return (
<button onClick={()=>addToTotalPrice('cheese',30)}>Click, totalPrice: {totalPrice}</button>
);
}
ReactDOM.render(<App />, document.body)
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
推荐阅读
- python - plotly python 中的 include_plotlyjs="cdn" 对生成的 HTML 有什么作用?
- python - Django 频道 - 如何从外部脚本向组发送消息?
- mysql - SUBSTRING 函数 mysql
- node.js - -bash: npm: 使用Node LTS安装包后找不到命令
- python - csv.writerow 在添加 for 循环后现在可以工作了吗?
- azure-devops-migration-tools - 使用 VSTS 同步迁移工具配置文件中的 DevOps 查询 ID 迁移 Azure DevOps 工作项
- sql - SQL:使用案例在单独的列中查找重复项和标记
- javascript - setState 函数没有有效地更新 rows 变量,因此它没有反映在 UI 中?
- python - 为什么在其包中导入的模块会带有自己的模块名称
- git - 从提交 ID 中查找父分支