反应:如何在功能组件中创建状态相关功能?

时间:2019-12-20 16:26:28

标签: javascript reactjs functional-programming react-functional-component

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

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中使用默认值-无法在此函数中获取更新状态。我如何组织我的代码来解决这个问题?

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函数时,setValuegetValue在第一次渲染时不可用:

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

2 个答案:

答案 0 :(得分:1)

编写custom hooks,将您的逻辑提取到单独的代码单元中。由于状态更改部分取决于先前的状态,因此应调用useReducer()而不是useState()来简化实现,并且状态更改是原子的:

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

    // this is important! your reference must be preserved (ew)
    oldState[attr] = val;
    return oldState;
  }, initialState);

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

  return { getValue, setValue, state };
};

我通常不建议更改状态对象,但是在这种情况下,由于您的useEffect()引用不断变化,因此您的state效率很低。如果有人知道如何解决此问题而不违反exhaustive-deps,请在下面发表评论。

现在您的useEffect()正在从第二个参数中删除依赖项。尽管有时会有有效的用例,但通常只会导致您当前遇到的问题。

我们也将您的useEffect()移入自定义钩子并进行修复:

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

      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, state]);
};

由于getValuesetValue是已记忆的,并且state是常量可变引用,因此实际更改的唯一依赖项是formControl,这很好。

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

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

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

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

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

答案 1 :(得分: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) );
            }
        }
    }, []);