背景
react祖父组件设置异步数据(setFieldsValue)后传递form给子组件,再逐层传递给孙子组件引起的未渲染异常,孙子组件如果不设置useEffect和useState去监听value的值进行重渲染,会出现获取得到value最新值,但是不进行渲染的异常
解决前后的代码对比
完整代码(异常):
javascript
const GetText = (props) => {
const { value, config, containerId, getFieldValue } = props;
const [itemValue, setItemValue] = useState(value);
const { formId } = config;
const getFormId = useCallback(
(suffix = '_param_countryPhoneCode') => {
if (Array.isArray(formId)) {
return [containerId, formId[0], `${formId[1]}${suffix}`];
}
return `${formId}${suffix}`;
},
[formId, containerId],
);
useEffect(() => {
const pObj = getFieldValue(getFormId()) || {};
if (!value.includes('+')) {
const _itemValue = `${pObj.countryPhoneCode ? '+' : ''}${pObj.countryPhoneCode} ${value}`;
setItemValue(_itemValue);
}
}, [getFieldValue, getFormId, value, getFieldValue(getFormId())]);
return itemValue ? (
<>
<div style={{ fontSize: 12 }}>{itemValue}</div>
</>
) : null;
};
完整代码(正常):
javascript
const GetText = (props) => {
const { value, config, containerId, getFieldValue } = props;
const [itemValue, setItemValue] = useState();
const { formId } = config;
const getFormId = useCallback(
(suffix = '_param_countryPhoneCode') => {
if (Array.isArray(formId)) {
return [containerId, formId[0], `${formId[1]}${suffix}`];
}
return `${formId}${suffix}`;
},
[formId, containerId],
);
// 注意,由于在changeRecordModal中有对变更记录表单项做了顺序标记,
// 因此formId会多一个序号,在变更记录弹窗里,首次加载可能因为更新是异步的导致value没有正常渲染,
// 所以这边必须借用useEffect和useState控制value的更新渲染
useEffect(() => {
const pObj = getFieldValue(getFormId()) || {};
if (!value.includes('+')) {
const _itemValue = `${pObj.countryPhoneCode ? '+' : ''}${pObj.countryPhoneCode} ${value}`;
setItemValue(_itemValue);
}
}, [getFieldValue, getFormId, itemValue, value]);
return itemValue ? (
<>
<div style={{ fontSize: 12 }}>{itemValue}</div>
</>
) : null;
};