【问题标题】:react hook for submit button not changing data提交按钮的反应钩子不改变数据
【发布时间】:2021-12-20 00:51:30
【问题描述】:

Form.jsx

...

const initialValues = {
    name: '',
    id: '',
    price: ''
}

const initialSD = {
    name: "Test Name",
    id: "Test ID",
    price: "Test Price"
}


const Form = () => {

const{
        values,
        setValues,
        handleInputChange
    }=useForm(initialValues);

const {
        sd,
        setSD,
        handleSubmit
    }=UseButton(initialSD);

    return(
        <EasybaseProvider ebconfig={ebconfig}>
            <React.Fragment>
                <div className="form-wrapper">
                    <form className={classes.root} autoComplete="off" onSubmit={handleSubmit(values)}>

...

UseButton.jsx

import React, { useState } from 'react'

export default function useButton(incomingSD) {

    const [sd, setSD] = useState(incomingSD);

    const handleSubmit = values => e => {
       
        e.preventDefault()
        console.log('1', sd); // gives current values
        console.log('2', values); // gives new values to be added
        setSD({
            'name': values.name,
            'id': values.id,
            'price': values.price
        }) // expecting this to set "sd" values to the new "values" values.
        console.log('3', sd); // logs the same old "sd" values and the content on the pages doesn't change to reflect the new values
      }


    return {
        sd,
        setSD,
        handleSubmit
    }
}

UseButton.jsx 中的setSD 没有像我期望的那样更改存储在sd 中的值,因此页面没有使用新数据进行更新。

我试图理解为什么会这样。在这个阶段,setSD 设置器似乎没有立即修改sd,但我不确定为什么会这样。

如果我使用sd = {name: 'new name', id: 'new id', price: 'new price'} 之类的东西,它会立即生效,并且页面上的数据会因此而改变。

我对使用 react state 并试图更好地了解它是如何产生这个问题的。

【问题讨论】:

    标签: reactjs react-hooks jsx use-state


    【解决方案1】:

    setState 是异步的。一旦事件处理程序完成,React 将安排更新(因为如果有许多 setState,React 可以更新一次组件)。这里有更深入的解释为什么反应以这种方式工作https://github.com/facebook/react/issues/11527#issuecomment-360199710

    在您的情况下,您可以在 setState 之前声明更新的对象并在之后使用它

    const updatedSD = {
       'name': values.name,
       'id': values.id,
       'price': values.price
    };
    setSD(updatedSD);
    console.log(updatedSD)
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2021-06-28
      • 2021-12-13
      • 1970-01-01
      • 2020-05-18
      • 2022-07-05
      • 2020-11-05
      • 2021-07-01
      • 1970-01-01
      相关资源
      最近更新 更多