简体   繁体   English

React - 无法使用 onClick 内的 setState 更新 state

[英]React - Can't update state using setState inside onClick

I can't update my state using setState inside an onClick event on a button.我无法在按钮上的 onClick 事件中使用 setState 更新我的 state。 I try to put and console.log inside the function and it work, but the setState doesn't work我尝试将console.log放在 function 中并且它可以工作,但是 setState 不起作用

I've tried two approaches, one is:我尝试了两种方法,一种是:

<button onClick={() => setColEdit("")} className="bg-red-500 text-white p-1">
    <i className="pi pi-times"></i>
</button>

two is:二是:

const cancelEdit = () => {
    setColEdit((edit) => edit = "123")
}
<button onClick={cancelEdit} className="bg-red-500 text-white p-1">
    <i className="pi pi-times"></i>
</button>

I try to put console.log inside the arrow function and it works, but the state isn't updated我尝试将console.log放在箭头 function 内并且它有效,但 state 未更新

I don't know what's wrong with my code or if there is something I don't know about how the setState works.我不知道我的代码有什么问题,或者我不知道 setState 是如何工作的。 Or there is another solution to my problem?或者我的问题有另一种解决方案? Thanks谢谢

EDIT So sorry, here is the full code编辑很抱歉,这是完整的代码

import { useState } from "react"
import { NumericFormat } from "react-number-format"

const Component: NextPageWithLayout= () => {

const [colEdit, setColEdit] = useState("")

const cancelEdit = () => {
    setColEdit("")
}

return (
    <span onClick={() => setColEdit("sk_123")}>
        {colEdit == "sk_123" ? (
        <form className="flex items-center gap-1">
            <input type={'text'} defaultValue={1000} autoFocus />
            <button onClick={cancelEdit} className="bg-red-500 text-white p-1">
                <i className="pi pi-times"></i>
            </button>
        </form>
                                                                                
    ) : (
        <NumericFormat
            value={1000}
            prefix="Rp "
            displayType='text'
            thousandSeparator='.'
            decimalSeparator=','
        />
    )}
    </span>

Hope your general component structure has atlease these codes:希望您的通用组件结构具有这些代码:

 const [col, setColEdit] = useState(1);

Full sample code:完整示例代码:

import { useState } from "react";

export default function App() {
  const [col, setColEdit] = useState(1);

  return (
    <div className="App">
      <button
        onClick={() => setColEdit("")}
        className="bg-red-500 text-white p-1"
      >
        <i className="pi pi-times">Click</i>
      </button>
      <h1>My Col Edit value is - {col}</h1>
    </div>
  );
}

It has to be a problem with your useState declaration一定是你的useState声明有问题

Here's a working example with 3 ways of doing what you are trying to do这是一个工作示例,其中包含 3 种方法来执行您想做的事情

https://codesandbox.io/s/upbeat-leakey-m4lgrd https://codesandbox.io/s/upbeat-leakey-m4lgrd

import { useState } from "react";

export default function App() {
  // use state declaration must look like this
  const [colEdit, setColEdit] = useState("zero");

  const handleClickOne = (e) => {
    setColEdit((previous) => (previous = "one"));
  };

  const handleClickTwo = (e) => {
    setColEdit("two");
  };

  return (
    <div className="App">
      <h1>{colEdit}</h1>
      <button onClick={handleClickOne}>One ?</button>
      <button onClick={handleClickTwo}>Two ?</button>
      <button onClick={() => setColEdit("three")}>Three ?</button>
    </div>
  );
}

Please check your state.请检查您的 state。

import { useState } from "react";
export default function App() {
  // Please check your state there must be an issue.
  const [colEdit, setColEdit] = useState("initialValue");

  const handleClick = (e) => {
    setColEdit("");
  };

  return (
    <div className="App">
      <button onClick={handleClick} className="bg-red-500 text-white p-1">
           <i className="pi pi-times"></i>
      </button>
    </div>
  );

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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