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

普通写法

原来在组件中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写法, 所以需要使用babel转码. 在react-native项目目录下创建.babelrc文件, 内容:

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

并在package.json中添加插件:

"devDependencies": {
    ...
    "babel-plugin-transform-decorators-legacy": "^1.3.4"
}

在组件中使用:

import { connect } from 'react-redux';
import { start, stop, 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);一下就能更清晰了.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容