加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

redux在react-native上使用(四)--connect使用

发布时间:2020-12-15 07:29:27 所属栏目:百科 来源:网络整理
导读:普通写法 原来在组件中 connect 连接redux的写法是: import { connect } from 'react-redux';import { start,stop,reset } from './actions';class Home extends Component { ... // dispatch一个action this.props.dispatch(reset()); ... const mapStateTo

普通写法

原来在组件中connect连接redux的写法是:

import { connect } from 'react-redux';
import { start,stop,reset } from './actions';

class Home extends Component {

    ...
    
    // dispatch一个action
    this.props.dispatch(reset());
    
    ...
    
    const mapStateToProps = state => ({
        timer: state.timer
    })
}

export default connect(mapStateToProps)(Home);

或者

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from './actions';

class Home extends Component {
    
    ...
    
    // dispatch一个action
    this.props.dispatch.reset();
    
    ...
    
    const mapStateToProps = state => ({
        timer: state.timer
    })
    
    const mapDispatchToProps = dispatch => ({
      dispatch: bindActionCreators(actions,dispatch)
    });
}

export default connect(mapStateToProps,mapDispatchToProps)(Home);

文艺写法

因为@connect()是超前的ES7写法,所以需要使用babel转码. 在react-native项目目录下创建.babelrc文件,内容:

{
  "presets": ["react-native"],"plugins": ["transform-decorators-legacy"]
}

因为connect是超前的ES7写法,"plugins": ["transform-decorators-legacy"] }

在组件中使用:

import { connect } from 'react-redux';
import { start,reset } from './actions';

@connect(state => ({ timer: state.timer }))
class Home extends Component {
    
    ...
    
    // dispatch一个action
    this.props.dispatch(start());
    
    ...
}

export default Home;

或者:

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from './actions';

@connect(
  state => ({ timer: state.timer }),dispatch => bindActionCreators(actions,dispatch),)
class Home extends Component {
    
    ...
    
    // dispatch一个action
    this.props.reset();
    
    ...
}

export default Home;

其中异同,可以console.log(this.props);一下就能更清晰了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读