在react中用装饰器来装饰connect
React connect 装饰 中用
2023-09-11 14:16:54 时间
假设我们在react中有如下header组件:
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import actions from './actions';
class Header extends PureComponent{
render(){
return (
<div>这是个组件</div>
)
}
}
const mapStateToProps = state => ({
todos:state.todos
})
const mapDispatchToProps = dispatch => ({
setTodos:value=>dispatch(actions.setTodos(value))
})
export default connect(mapStateToProps,mapDispatchToProps)(Header)
我们在写react组件时结合redux要定义mapStateToProps和mapDispatchToProps两个返回对象的纯函数以便交给connect去包裹使用 具体connect使用查看connect
这里我们就可以用装饰器(Decorator)来改写下:
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import actions from './actions';
@connect(
state=>({
todos:state.todos
}),
dispatch=>({
setTodos:value=>dispatch(actions.setTodos(value))
})
)
class Header extends PureComponent{
render(){
return (
<div>这是个组件</div>
)
}
}
export default Header
如此,改造完成,代码看上去也比改造前的干净整洁了
但是由于装饰器的兼容性问题我们需要使用babel来转换
```// 安装babel插件 yarn add @babel/plugin-proposal-decorators ```修改package.json下的babel
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
},
最后一步
根目录下新建jsconfig.json解决编辑器报错问题
{
"compilerOptions": {
"experimentalDecorators": true
}
}
然后就可以愉快的coding了
相关文章
- React系列——websocket群聊系统在react的实现
- react 移动端 兼容性问题和一些小细节
- [React] Using react-styleguidist for Component demo
- [React Testing] Mock react-transition-group in React Component Tests with jest.mock
- [React + Functional Programming ADT] Connect State ADT Based Redux Actions to a React Application
- [React Intl] Format a Date Relative to the Current Date Using react-intl FormattedRelative
- [React Intl] Format Date and Time Using react-intl FormattedDate and FormattedTime
- [React Intl] Install and Configure the Entry Point of react-intl
- [React] Create a Virtualized List with Auto Sizing Cells using react-virtualized and CellMeasurer
- [Redux] Generating Containers with connect() from React Redux (FooterLink)
- [React Testing] Intro to Shallow Rendering
- [React] React Fundamentals: State Basics
- React Native开发技术
- [React] React hook, component props for refactoring
- [React] React Virtual
- [React Testing] Using __mocks__ to mock the promise based API
- [React Testing] Use React Testing Library’s Wrapper Option to Simplify using rerender
- [React GraphQL] Pass Parameters to urql's useQuery React Hook
- [Recompose] Stream Props to React Children with RxJS
- [React Intl] Use a react-intl Higher Order Component to format messages
- [React Intl] Format Date and Time Using react-intl FormattedDate and FormattedTime
- [React] Use React ref to Get a Reference to Specific Components
- atitit.React 优缺点 相比angular react是最靠谱的web ui组件化方案了
- 如何得到React应用转换后的JavaScript代码
- react源码分析:深度理解React.Context
- 使用React做一个音乐播放器
- 【taro react hooks 错误解决】---- Warning: Can‘t perform a React state update on an unmounted component.