【问题标题】:React setstate not updating in functional componentReact setstate 未在功能组件中更新
【发布时间】:2022-11-22 07:54:44
【问题描述】:

在功能组件中,我有 onchange 函数,我正在更新状态但状态不会立即更新,这意味着首先如果我输入第一个字符,它会在我输入第二个字符时反映出来,我如何立即更新它。

 const [customstartdate, setCustomstartdate] = useState();
  const [customenddate, setCustomenddate] = useState();
<Input
                      className={`form-control-digits not-empty`}
                      onChange={customHandler}
                      type="date"
                      id="meeting-time"
                      name="start_date"
                    />

const customHandler = (e) => {
    if (e.target.name === "start_date") {
      setCustomstartdate(e.target.value);
    }
    if (e.target.name === "end_date") {
      setCustomenddate(e.target.value);
    }
    //having some functionality here
  };

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

你可以使用这样的东西

useEffect(() => {
setName(eve.target.value)

}, [eve.target.value])

【讨论】:

    【解决方案2】:

    请在google上搜索如何使用react hooks,

    当你使用onChange他不能直接运行你的功能, 您需要编写一个运行您的函数的回调,

    请按照我的例子阅读更多关于反应

    const [name,setName] = useState("");
    <div>
            <label>name</label>
            <input type="text" id="fname" onChange={(eve)=>setName(eve.target.value)}/>
    </div>
    

    在这个例子之后,你可以看到我正在使用一个回调函数来使用 useState

    【讨论】:

    • onChange={customHandler} 非常好。它是一个函数,当更改触发它时会调用它(与具有内联函数或箭头函数没有区别)。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2020-09-15
    • 2021-04-20
    • 1970-01-01
    • 2014-04-19
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多