在我的应用程序中,我有这样的组件:
const MyComponent = props => {
const { attrOneDefault, attrTwoDefault, formControl } = props;
const [inputValue, setInputValue] = useState({
attr_one: attrOneDefault,
attr_two: attrTwoDefault
});
const getValue = ( attr ) => {
return inputValue[attr];
}
const setValue = ( attr, val ) => {
if( attr === 'attr_one' ) {
if( val === 'bar' && getValue(attr) !== 'foo' ) {
val = 'foo bar';
}
}
setInputValue( {...inputValue, [attr]: val} );
}
useEffect( () => {
if( formControl ) {
Object.keys(inputValue).forEach( attribute => {
formControl.subscribeToValueCollecting( attribute, () => {
return getValue(attribute);
});
formControl.subscribeToValueChange( attribute, ( value ) => {
setValue( attribute, value );
return true;
});
});
}
return () => {
if( formControl ) {
Object.keys(inputValue).forEach( attribute => formControl.unsubscribe(attribute) );
}
}
}, []);
return (
<div class="form-field">
<input
type="text"
value={getValue('attr_one')}
onChange={ e => setValue('attr_one', e.target.value)}
/>
<input
type="checkbox"
checked={getValue('attr_two')}
onChange={ e => setValue('attr_two', !!e.target.checked)}
/>
</div>
);
}
在函数内部setValue
,getValue
我总是有默认值inputValue
- 我无法在这个函数内部获得更新的状态。我如何组织我的代码来解决这个问题?
附言
1)使用 useCallback 我有相同的结果:
const getValue = useCallback( ( attr ) => {
return inputValue[attr];
}, [inputValue]);
const setValue = useCallback( ( attr, val ) => {
if( attr === 'attr_one' ) {
if( val === 'bar' && getValue(attr) !== 'foo' ) {
val = 'foo bar';
}
}
setInputValue( {...inputValue, [attr]: val} );
}, [inputValue]);
2) 使用 useEffect 功能setValue
并且getValue
在第一次渲染时不可用:
let getValue, setValue;
useEffect( () => {
getValue = ( attr ) => {
return inputValue[attr];
}
setValue = ( attr, val ) => {
if( attr === 'attr_one' ) {
if( val === 'bar' && getValue(attr) !== 'foo' ) {
val = 'foo bar';
}
}
setInputValue( {...inputValue, [attr]: val} );
}
}, [inputValue]);