ReactNative进阶(八):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...
普通写法
原来在组件中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);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
或者
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);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
精简写法
因为@connect()
是超前的ES7
写法, 所以需要使用babel
转码。在react-native
项目目录下创建.babelrc
文件, 内容:
{
"presets": ["react-native"],
"plugins": ["transform-decorators-legacy"]
}
- 1
- 2
- 3
- 4
并在package.json
中添加插件:
"devDependencies": { ... "babel-plugin-transform-decorators-legacy": "^1.3.4"
}
- 1
- 2
- 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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
或者:
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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
其中异同, 可以console.log(this.props);
一下就能更清晰了。
拓展阅读
文章来源: shq5785.blog.csdn.net,作者:No Silver Bullet,版权归原作者所有,如需转载,请联系作者。
原文链接:shq5785.blog.csdn.net/article/details/116146161
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)