React-redux装饰器用法:@connect之妙用
Author:zhoulujun Date:
基本概念科普
Provider
React-Redux 提供<Provider/>组件,能够使整个app访问到Redux store中的数据。
Provider是用context封装的。
connect
React-Redux提供一个connect方法能够把组件和store连接起来,把state,dispatch方法,捏合到当前组件上。
connect有两个参数,两参数都是函数,参数在connect内部被调用,参数内能拿到state和dispatch,详见代码示例。
connect调用的返回结果是一个高阶组件。
更多的,可以阅读:
redux的几个基本概念 https://juejin.cn/post/6844904200225161223
https://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
基本用法
redux 用法很简单:https://react-redux.js.org/tutorials/quick-start
普通用法
const mapStateToProps = (state, ownProps) => ({ todo: state.todos[ownProps.id], }) const mapDispatchToProps = (dispatch) => { return { // dispatching plain actions increment: () => dispatch({ type: 'INCREMENT' }), decrement: () => dispatch({ type: 'DECREMENT' }), reset: () => dispatch({ type: 'RESET' }), } } export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
在函数式组件里面
import React from 'react' import { useSelector, useDispatch } from 'react-redux' import { decrement, increment } from './counterSlice' import styles from './Counter.module.css' export function Counter() { const count = useSelector((state) => state.counter.value) const dispatch = useDispatch() return ( <div> <div> <button aria-label="Increment value" onClick={() => dispatch(increment())} > Increment </button> <span>{count}</span> <button aria-label="Decrement value" onClick={() => dispatch(decrement())} > Decrement </button> </div> </div> ) }
react项目用@connect装饰器
conncet是从react-redux中结构出来的一个装饰器,用来实现不同页面(或组件)的数据共享,避免组件间一层层的嵌套传值。
import React from 'react' import {render} from 'react-dom' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import action from 'action.js' class App extends React.Component{ render(){ return <div>hello</div> } } function mapStateToProps(state){ return state.main } function mapDispatchToProps(dispatch){ return bindActionCreators(action,dispatch) } export default connect(mapStateToProps,mapDispatchToProps)(App)
改用装饰器
import React from 'react' import {render} from 'react-dom' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import action from 'action.js' @connect( state=>state.main, dispatch=>bindActionCreators(action,dispatch) ) class App extends React.Component{ render(){ return <div>hello</div> } }
不过不知为何会报这个错误;
TS1238: Unable to resolve signature of class decorator when called as an expression. Type 'ConnectedComponent<typeof Index, Omit<ClassAttributes<Index> & PageProps, "user">>' is not assignable to type 'typeof Index'. Type 'NamedExoticComponent<Omit<ClassAttributes<Index> & PageProps, "user">> & NonReactStatics<typeof Index, {}> & { ...; }' provides no match for the signature 'new (props: any): Index'.
目前暂时没有得到解决
参考文章:
深入浅出之React-redux中connect的装饰器用法@connect https://juejin.cn/post/6844903742723063822
转载本站文章《React-redux装饰器用法:@connect之妙用》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/jsBase/2021_1117_8712.html