javascript - 如何从重组转换为钩子?
问题描述
我的公司正在使用 recompose 作为我们的状态管理工具。我们正在重构我们的应用程序以使用钩子。对于下面的代码,您如何将 recompose 组件替换为 react hook 组件?
我明白withState变成了useState,比如:
withState('something', 'setSomething', null)
变成
const [something, setSomething] = useState(null);
withProps
, withHandlers
,compose
和hoistStatics
会lifecycle
变成什么?
将如何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);
解决方案
引用丹·阿布拉莫夫的话:
为了提高工作效率,您需要“思考效果”,他们的心智模型更接近于实现同步,而不是响应生命周期事件。
我们不能 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`);
}
}
推荐阅读
- github - github 上的虚幻引擎源代码 404 错误页面未找到
- javascript - 导航栏手风琴链接不起作用
- visual-studio - 在当前项目路径中打开命令提示符的 Visual Studio 快捷方式
- angular - 使用角度 4 从 FileReader onload 函数内部返回一个布尔值
- javascript - TypeScript:映射强类型集合
- python - 错误“-: 'str' 和 'float' 的操作数类型不受支持?
- r - Extract first N digits from a string
- python - 无法将 tensorflow 导入 python 3.5(在 2.7 中成功导入)
- ios - 丰富的推送通知不适用于 IOS 中的 FCM
- c# - 计时器计数无法正常工作