项目作者: NoamELB

项目描述 :
React getDerivedStateFromProps implementation to make Controllable components 💡
高级语言: JavaScript
项目地址: git://github.com/NoamELB/make-controllable.git
创建时间: 2017-12-16T15:15:34Z
项目社区:https://github.com/NoamELB/make-controllable

开源协议:MIT License

下载


make-controllable

Implementing the exact same getDerivedStateFromProps over and over again to make Controllable components can be very repetitive.

make-controllable is a function to help make your components Controllable.

What is Controllable? Read this: https://medium.com/myheritage-engineering/how-controllable-react-components-maximize-reusability-86e3d233fa8e

This repetitive code:

  1. static getDerivedStateFromProps(props, state) {
  2. let newState = null;
  3. if (props.value !== state.prevValue) {
  4. newState = { prevValue: props.value };
  5. if (props.value !== state.value) {
  6. newState.value = props.value;
  7. }
  8. }
  9. return newState;
  10. }

Can be shorten to this one line:

  1. static getDerivedStateFromProps(props, state) {
  2. return makeControllable(props, state, 'value');
  3. }

Live example here: https://codesandbox.io/s/w0mjk9z63k

Install

  1. npm i make-controllable

Usage

Function parameters

  1. import makeControllable from 'make-controllable';
  2. return makeControllable(props, state, propsMapping);

Parameters

  • props - the 1st argument from getDerivedStateFromProps
  • state - the 2nd argument from getDerivedStateFromProps
  • propsMapping - Object | String, mapping of prop key name to state key name. Or a String for a single prop with the same state key.

Examples

Making props.value Controllable on state.value:

  1. static getDerivedStateFromProps(props, state) {
  2. return makeControllable(props, state, 'value');
  3. }

Making props.value Controllable on state.otherValue:

  1. static getDerivedStateFromProps(props, state) {
  2. return makeControllable(props, state, {'value': 'otherValue'});
  3. }

With multiple props:

  1. static getDerivedStateFromProps(props, state) {
  2. makeControllable(props, state, {
  3. 'value': 'otherValue',
  4. 'value2': 'otherValue2',
  5. });
  6. }

License

MIT