When I click on <a onClick{() => "function"}> for the first time, everything is fine, but when I click for the second time, everything breaks. Here I got the code:
function ref(sub) { console.log(Subjects) SetSubjects(Subjects[sub] = true) console.log(Subjects) }; const [Subjects, SetSubjects] = useState({ "Mathematics": false, "Physics": false, "Ukranian": false, "English": false, "Chemistry": false, "Informatics": false, "History": false }) return ( <div className="area"> <div className="logo_header"><a className="logo_header_text" href="/">Owly</a></div> <h1 className="tittle">Choose the Subject</h1> <div className="select_btns"> <a onClick={() => ref("Mathematics")} >Mathematics</a> <a onClick={() => ref("Physics")} >Physics</a> <a onClick={() => ref("Ukranian")} >Ukranian</a> <a onClick={() => ref("English")} >English</a> <a onClick={() => ref("Chemistry")}>Chemistry</a> <a onClick={() => ref("Informatics")}>Informatics</a> <a onClick={() => ref("History")}>History</a> </div>
Here I have a screen First click:
Second click:
It doesn’t matter which button I choose
P粉8659009942024-02-22 18:57:45
This doesn't go the way you think:
SetSubjects(Subjects[sub] = true)
The result
of the expression Subjects[sub] = true is the value true
, so you set Subjects
to the value true
. Of course, it doesn't have any of the properties you'd expect from a Subjects
object.
I suspect you are looking for this:
SetSubjects({ ...Subjects, [sub]: true })
This will set Subjects
to an object containing all properties on the current Subjects
and set the properties defined by the values in sub
to true
.