closeBet 方法在我点击它时似乎没有触发任何东西。谁能解释我为什么?我想我正确地实施了一切只是不明白为什么不能正常工作。甚至其他 useState isActive 也没有完成它的工作。那么我应该怎么做才能在点击时正确更改 useState。提前致谢
import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import FilterMenu from "./selectButton";
import FetchRandomBet from "./fetchRandomBets";
function Betslip() {
const data = [
{
value: 0,
label: "No Filter"
},
{
value: 1,
label: "Less than two"
},
{
value: 2,
label: "More than two"
},
]
const [selectedValue, setSelectedValue] = useState(0);
const [allStakes, setAllStakes] = useState(null);
const [isActive, setActive] = useState("false");
const handleChange = obj => {
setSelectedValue(obj.value);
}
const betNow = () => {
if (!allStakes) {
const stakes = localStorage.getItem("stakes");
const jsnStake = JSON.parse(stakes) || [];
setAllStakes([jsnStake]);
setActive(isActive);
console.log('yes')
} else if (allStakes) {
localStorage.setItem("stakes", null);
setAllStakes([])
console.log('no')
}
}
const closeBet = () => {
setActive("false");
}
console.log(allStakes)
return (
<div className="betslip">
<div className="betslip-top">
<h1 className="text">BETSLIP</h1>
<p className="text-two">BET WITH US!</p>
<div>
<FilterMenu
optionsProp={data}
valueProp={selectedValue}
onChangeProp={handleChange}
/>
</div>
</div>
<div>
<FetchRandomBet
valueProp={selectedValue}
/>
</div>
<Button
onClick={betNow}
className="betnow"
variant="contained"
>
Bet Now!
</Button>
<div className={isActive ? "bet-show" : "bet-noshow"}>
<button
onClick={closeBet}>
x
</button>
<h1>
{allStakes}
</h1>
</div>
</div >
);
}
export default Betslip;
答案 0 :(得分:3)
您的 isActive 状态使用 string
而不是 boolean
值。应该是这样的:
const [isActive, setActive] = useState(false);
以及更新状态时:
const closeBet = () => {
setActive(false);
}
删除 false
值周围的引号,它应该可以按预期工作。
答案 1 :(得分:2)
您可能希望将该值设置为 false
,因此您不应使用引号,因为它会变成字符串。
setActive(false);