原來在組件中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