【发布时间】:2020-04-13 03:48:01
【问题描述】:
在我的应用程序中,我有这样的组件:
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 中有默认值 - 我无法在这些函数内部获取更新状态。我如何组织我的代码来解决这个问题?
P。
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]);
【问题讨论】:
-
为什么你的
setValue()里面有看似随机的逻辑? -
这只是一个例子——这个函数有一些逻辑。我想让代码更短更容易理解。
-
你的
useEffect正在捕获你的inputValue,这就是为什么它总是一样的。尝试将inputValue传递到您的使用效果数组[] -
对 formControl.subscribe... 监听器使用 Ref 回调
标签: javascript reactjs functional-programming react-functional-component