普通寫法
原來在元件中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"]
}
在元件中使用:
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);
一下就能更清晰了.