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

普通寫法

原來在組件中connect鏈接redux的寫法是:react

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);

或者redux

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文件, 內容:react-native

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

由於connect是超前的ES7寫法, 因此須要使用babel轉碼. 在react-native項目目錄下建立.babelrc文件, 內容:babel

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

在組件中使用:this

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;

或者:spa

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);一下就能更清晰了.code

相關文章
相關標籤/搜索