2

在我的应用程序中,我有这样的组件:

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>
    );
}

在函数内部setValuegetValue我总是有默认值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]);
4

2 回答 2

2

编写自定义挂钩以将您的逻辑提取到单独的代码单元中。由于您的状态更改部分依赖于先前的状态,因此您应该调用useReducer()而不是useState()使实现更容易并且状态更改是原子的:

const useAccessors = initialState => {
  const [state, dispatch] = useReducer((prev, [attr, val]) => {
    if (attr === 'attr_one') {
      if (val === 'bar' && getValue(attr) !== 'foo') {
        val = 'foo bar';
      }
    }

    return { ...prev, [attr]: val };
  }, initialState);
  const ref = useRef(state);

  useEffect(() => {
    ref.current = state;
  }, [ref]);

  const getValue = useCallback(
    attr => ref.current[attr],
    [ref]
  );
  const setValue = useCallback((attr, val) => {
    dispatch([attr, val]);
  }, [dispatch]);

  return { getValue, setValue, ref };
};

现在,您useEffect()从第二个参数中省略了依赖项。这往往会导致您目前遇到的问题。我们可以雇用useRef()来解决这个问题。

让我们也将您移动useEffect()到自定义钩子中并修复它:

const useFormControl = (formControl, { getValue, setValue, ref }) => {
  useEffect(() => {
    if (formControl) {
      const keys = Object.keys(ref.current);

      keys.forEach(attribute => {
        formControl.subscribeToValueCollecting(attribute, () => {
          return getValue(attribute);
        });
        formControl.subscribeToValueChange(attribute, value => {
          setValue(attribute, value);
          return true;
        });
      });

      return () => {
        keys.forEach(attribute => {
          formControl.unsubscribe(attribute);
        });
      };
    }
  }, [formControl, getValue, setValue, ref]);
};

由于getValue,setValueref被记忆,唯一真正改变的依赖是formControl, 这很好。

将所有这些放在一起,我们得到:

const MyComponent = props =>
  const { attrOneDefault, attrTwoDefault, formControl } = props;

  const { getValue, setValue, ref } = useAccessors({
    attr_one: attrOneDefault,
    attr_two: attrTwoDefault
  });

  useFormControl(formControl, { getValue, setValue, ref });

  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>
  );
};
于 2019-12-20T17:19:08.533 回答
0

试试这个:

const getValue = ( attr ) => {
        return inputValue[attr];
    }
const getValueRef = useRef(getValue)
const setValue = ( attr, val ) => {
        setInputValue( inputValue =>{
            if( attr === 'attr_one' ) {
                if( val === 'bar' && inputValue[attr] !== 'foo' ) {
                    val = 'foo bar';
                }
            }
            return {...inputValue, [attr]: val} );
        }
}

useEffect(()=>{
    getValueRef.current=getValue
})

    useEffect( () => {
        const getCurrentValue = (attr)=>getValueRef.current(attr)
        if( formControl ) {         
            Object.keys(inputValue).forEach( attribute => {
                formControl.subscribeToValueCollecting( attribute, () => {
                    return getCurrentValue(attribute);
                });
                formControl.subscribeToValueChange( attribute, ( value ) => {
                    setValue( attribute, value );
                    return true;
                });
            });
        }

        return () => { 
            if( formControl ) {
                Object.keys(inputValue).forEach( attribute => formControl.unsubscribe(attribute) );
            }
        }
    }, []);

于 2019-12-20T17:18:59.663 回答