首页 > 解决方案 > 如何从重组转换为钩子?

问题描述

我的公司正在使用 recompose 作为我们的状态管理工具。我们正在重构我们的应用程序以使用钩子。对于下面的代码,您如何将 recompose 组件替换为 react hook 组件?

我明白withState变成了useState,比如:

withState('something', 'setSomething', null)

变成

const [something, setSomething] = useState(null);

withProps, withHandlers,composehoistStaticslifecycle变成什么?

将如何mapStateToProps工作mapDispatchToProps

import { compose, hoistStatics, withHandlers, withState, withProps, lifecycle } from 'recompose';
import { connect } from 'react-redux'
import myComponent from './myComponent'

const mapStateToProps = (state, props) => {
  return {

  }
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({

  }, dispatch)
};

const enhancer = compose(
  connect(mapStateToProps,mapDispatchToProps),
  withProps(props => ({
    myProp: props.myProp,
  })),
  withState('something', 'setSomething', null),
  withState('somethingElse', 'setSomethingElse', null),
  withHandlers({
    myFunction: () => () => {
      console.log(`I need help`);
    }
  }),
  lifecycle({
    componentDidMount() {

    },
    componentDidUpdate() {

    }
  })
);

export default hoistStatics(enhancer)(myComponent);

标签: javascriptreactjsreact-nativereact-hooksrecompose

解决方案


引用丹·阿布拉莫夫的话:

为了提高工作效率,您需要“思考效果”,他们的心智模型更接近于实现同步,而不是响应生命周期事件。

我们不能 1:1 替换 hooks 和 hocs,因为它们是不同的编程模型。不过,我们可以尝试通过以下方式迁移:

withProps- 可以在组件内替换为 const

withHandlers- 可以替换为组件内的箭头函数

lifecycle- https://stackoverflow.com/a/55502524/3439101

一个简单的例子(不是所有的情况):

临时工_

const enhancer = compose(
  withProps(props => ({
    myProp: props.myProp,
  })),
  withState('something', 'setSomething', null),
  withHandlers({
    myFunction: () => () => {
      console.log(`I need help`);
    }
  }),
  lifecycle({
    componentDidMount() {
      console.log('mounted')
    }
  })
);

挂钩

const MyComponent = props => {
  const [something, setSomthing] = useState(null)

  useEffect(() => {
    console.log('mounted')
  }, [])

  const myProp = props.myProp

  const myFunction = () => {
    console.log(`I need help`);
  }
}

推荐阅读