简体   繁体   中英

React js : My state is not changing after onClick

when I onClick, my state: changeSybmol is not changing to true but remains false.

In summary I just want my state to update to false if it is true or vice versa.

import React, { useState } from "react";
import "./Box.css";

function Box(props) {
  const [symbol, setSymbol] = useState("");
  const [changeSymbol, setChangeSymbol] = useState(false);

  function handleClick() {
    if (symbol === "") {
      if (!changeSymbol) {
        setChangeSymbol(true);
        setSymbol("X");
        console.log(changeSymbol);
      } else {
        setSymbol("O");
        setChangeSymbol(false);
      }
    }
  }

  return (
    <div key={props.key} onClick={handleClick} className="box">
      {symbol}
    </div>
  );
}
export default Box;



Remove the first if statement and it works.

import React, { useState } from "react";

function Box(props) {
  const [symbol, setSymbol] = useState("");
  const [changeSymbol, setChangeSymbol] = useState(false);

  function handleClick() {
      if (!changeSymbol) {
        setChangeSymbol(true);
        setSymbol("X");
        console.log(changeSymbol);
      } else {
        setSymbol("O");
        setChangeSymbol(false);
      }
    
  }

  return (
    <div key={props.key} onClick={handleClick} className="box">
      {symbol}
    </div>
  );
}
export default Box;

Why are you using following piece of code?

if (symbol === "") {}

This is not allowing your code to execute futher once the symbol is set. Remove this & your code will run fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM