【发布时间】: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