reactjs - 反应钩子不改变表单值
问题描述
React 新手并致力于现有项目。我希望当 Select Elment 更改(正确调用 onInstrumentSelected)时,用其相关值填充表单的其他字段,但不起作用。我可以获得正确的数据(在 console.log 中检查),但无法通过相关的新数据重新填写表格。
const { Option, OptGroup } = Select;
const SettingsViewComponent: React.FC<{ base_instruments: any }> = props => {
let [settings, setSettings] = React.useState<ISettings>();
const instSearch = props.base_instruments;
let insId = 0;
React.useEffect(() => {
async function fetchsettings(ins) {
getSettings(ins)
.then(rsp => {
setSettings(rsp.data);
});
}
fetchsettings(insId)
}, [insId]);
const onInstrumentSelected = async (value, option) => {
insId = option.value;
const stt= await getSettings(option.value);
if (stt!= null) {
console.log(stt.data); //correct data here
// not working part:
settings = stt.data
setSettings(stt.data);
} else {
message.error('error');
}
};
return !settings ? (
<div />
) : (
<Form
initialValues={settings}
onFinish={onFinish}
onFinishFailed={onFinishFailed}>
<Form.Item label="instrument" name="instrumentId">
<Select onSelect={(val, op) => onInstrumentSelected(val, op)}>
{instOptions}
</Select>
</Form.Item>
<Form.Item label="Field 1" name="field1" >
<Input />
</Form.Item>
<Form.Item label="Field 2" name="field2" >
<Input />
</Form.Item>
<Form.Item label="Field3" name="field3">
<Input />
</Form.Item>
</Form>);};
export default SettingsViewComponent;
解决方案
我从ant.design找到了解决方案并解决了如下问题,关键更改是setFieldsValue
在表单上使用:
// some unchanged
const [form] = Form.useForm();
const onInstrumentSelected = async (value, option) => {
const stt= await getSettings(option.value);
if (stt!= null) {
console.log(stt.data); //correct data here
settings = stt.data
form.setFieldsValue({ field1: settings.field1});
form.setFieldsValue({ field2: settings.field2});
form.setFieldsValue({ field3: settings.field3});
} else {
message.error('error');
}
};
return !settings ? (
<div />
) : (
<Form form={form}
// unchanged
推荐阅读
- django - Channel Worker 崩溃:崩溃前如何做一些任务?
- jquery - 如何将数据从我的网站发送到我的 Arduino netshield
- python - Zlib 库图像压缩无法正常工作
- c# - C# 中的 OfficeOpenXML EPPlus - Excel 文件在写入一定大小的数据后会损坏
- node.js - 如果值是重复的 DynamoDB,则删除一行
- list - 列表减法过程中丢失的元素
- ruby - For 循环和 if 在 puts 函数中 - Ruby
- tensorflow - 在数据帧上运行 Universal-sentence-encoder-large 迭代时内存泄漏
- python - 即使在 KeepAspectRatio 和 SmoothTransition 之后如何在 QPixmaps 上获得更好的图像质量
- html - 如何在小视口上显示图像下方的文本?