【发布时间】:2020-09-07 15:29:32
【问题描述】:
我有一个带有 useEffect 的 react 组件,它在 props 更改时不会被触发。我希望这个组件根据道具更新它显示的内容。但是,当 prop 发生变化时,什么都不会发生。
为了调试,我添加了一个可以手动更新值的按钮,效果很好。我只是无法让 useEffect 为我的生命运行。
const ReadOnly = (props: WidgetProps) => {
const [value, setValue] = React.useState('No Value');
const { formContext } = props;
const firstName = () => formContext.queryData[0]?.basicInformation?.firstName ?? 'No value';
// This only runs once when the component is first rendered never fired when formContext updates.
React.useEffect(() => {
setValue(firstName());
}, [formContext]);
// This correctly updates the value
const onClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
e.preventDefault();
setValue(firstName());
};
return (
<>
<p>{value}</p>
<Button onClick={onClick}>Update Value</Button>
</>
);
};
export default ReadOnly;
我尝试将 useEffect 函数监视的值从 formContext 更改为 formContext.queryData[0].basicInformation.firstName 无效。我也尝试过使用props。我什至尝试完全删除手表阵列,希望它只是垃圾邮件更新,但没有。
关于如何实现这一目标的任何建议?我知道该值正在传递给组件,因为它在我按下按钮时起作用。当我在网页上的 React 检查器中检查它时,我可以清楚地看到该值在那里。干杯。
编辑:
该组件被用作 react-jsonschema-form 的小部件。基本上,每次更新formData 时,我都会将其传回formContext。 formContext 是我可以将其他数据获取到该小部件的唯一方法。下面是我正在做的精简版。
const [formDataAndIncludings, setFormDataAndIncludings] = React.useState<any>(null);
ClientRect.useEffect(() => {
...
// Initial loading of formDataAndIncludings
...
}, [])
const onChange = (e: IChangeEvent<any>) => {
const newFormDataAndIncludings = { ...formDataAndIncludings };
newFormDataAndIncludings.queryData[0] = e.formData;
setFormDataAndIncludings(newFormDataAndIncludings);
};
return (
<Form
...
onChange={onChange}
formContext={formDataAndIncludings}
...
/>
)
【问题讨论】:
-
你能说明你是如何更新 formContext 的吗?
-
@AtinSingh,我已经更新了我的帖子以显示它是如何更新的。
标签: reactjs react-props use-effect react-jsonschema-forms