我在更改 select
的值后更新我的状态对象。它为对象设置了正确的值,但不在浏览器中更新(输入字段)。
import React, { useState, useEffect } from 'react';
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input, Alert } from 'reactstrap';
import NumberFormat from 'react-number-format';
// More imports
const AddUser = (props) => {
const propID = props.propID;
// The object has more properties. I'm just showing the ones related to the issue
const [ addUser, setAddUer ] = useState({
unitID: 0,
adminFee: 0
});
const [ units, setUnits ] = useState([]);
useEffect(() => {
async function fetchData() {
// this method is an axios request to grab data
const data = await myAxios.getUnits(propID);
setUnits(data);
}
fetchData();
}, [propID]);
const handleUnitChange = async (id) => {
const unitCharges = await myAxios.getUnitCharges(parseInt(id));
if(unitCharges !== null) {
setAddUer ({
...addUser,
unitID: id,
adminFee: parseFloat(unitCharges.AdminFee).toFixed(2)
});
}
}
// There is a lot of other fields and style here.
// I'm showing just the related fields
return (
<>
<Label for="unit" className="mr-sm-10">Unit</Label>
<Input type="select" name="unit" id="unit"
value={addUser.unitID} onChange={(e) => handleUnitChange(e.target.value)}
innerRef={register({ required: true })}
>
<option value="0">Select</option>
{units.map((obj) => {
return (
<option
key={obj.UnitID}
value={obj.UnitID}
>
{obj.UnitName}
</option>
);
})}
</Input>
<Label for="admin" className="mr-sm-10">Admin</Label>
<Controller
as={
<NumberFormat
thousandSeparator={true}
prefix={"$"}
onValueChange={(v) => {
setAddUer({...addUser, adminFee: v.floatValue === undefined ? 0 : v.floatValue})
}}
/>
}
name="admin"
id="admin"
variant="outlined"
defaultValue={addUser.adminFee}
getInputRef={register({ required: true })}
control={control}
className="form-control"
/>
</>
);
};
export default AddUser;
用数组代替 Axios 请求的 SandBox:https://codesandbox.io/s/weathered-star-3i9u4?file=/src/App.js
答案 0 :(得分:1)
请尝试将代码的 Controller 部分替换为以下代码。
<Controller
name="admin"
id="admin"
variant="outlined"
getInputRef={register({ required: true })}
control={control}
className="form-control"
value={addUser.adminFee}
render={({ field }) => (
<NumberFormat
thousandSeparator={true}
prefix={"$"}
value={addUser.adminFee}
onValueChange={(v) => {
setAddUer({
...addUser,
adminFee: v.floatValue === undefined ? 0 : v.floatValue
});
}}
/>
)}
/>