Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
72 lines (63 sloc) 1.05 KB

React hooks using decorators

this is one of my thinking, not so much accurate.

@set.state('foo', null)
class Component {
  @effect([])
  @inject.props()
  @inject.state('foo')
  onMounted = (props, [foo, setFoo]) => {
    setFoo(fetch(props.api).then(res => res.data))
  }

  @inject.state('foo')
  render ([foo]) {
    return (
      <div>
        {foo}
      </div>
    )
  }
}

is same as

const Component = props => {
  const [foo, setFoo] = useState(null) 
  useEffect(() => {
    fetch(props.api).then(res => setState(res.data))
  }, [])
  return (
    <div>
      {foo}
    </div>
  )
}

Step

class C {
  @inject.state('foo')
  render ([foo, setFoo]) {
    return (
      <div>
        {foo}
      </div>
    )
  }
}
export const inject = {
  state: name => {
    return (target, key, desc) => {
      const originalValue = desc.value
      const desc.value = () => {
        const v = target[stateFindSymbol](name)  // find that state
        originalValue.call(null, v)
      }
      return desc
    }
  }
}
You can’t perform that action at this time.