react redux

亦凉 2022-02-19 00:39 299阅读 0赞

在react中使用redux入门。
基本的例子使用redux管理react的状态。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Hello React!</title>
  6. <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
  7. <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
  8. <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
  9. <script src="https://cdn.bootcss.com/redux/4.0.1/redux.js"></script>
  10. </head>
  11. <body>
  12. <div id="example"></div>
  13. <script type="text/babel"> const initialState = { cart: [ { product: 'bread 700g', quantity: 2, unitCost: 90 }, { product: 'milk 500ml', quantity: 1, unitCost: 47 } ] } const ADD_TO_CART = 'ADD_TO_CART' const renducer = function (state=initialState, action) { switch (action.type) { case ADD_TO_CART: return { ...state, cart:[...state.cart, action.payload], } default: return state; break; } } const store = Redux.createStore(renducer) //class声明组件 class ClassComponent extends React.Component { addToCart(product, quantity, unitCost){ store.dispatch({ type:ADD_TO_CART, payload:{ product, quantity, unitCost } }) } render(){ return ( <div> <h1>{ this.props.v1}--{ store.getState().cart.length}</h1> <button onClick={ ()=>{ this.addToCart('coffee1',1,100)}}>addToCart1</button> <button onClick={ ()=>{ this.addToCart('coffee2',2,200)}}>addToCart2</button> </div> ) } } const render = ()=>{ ReactDOM.render( <div> <ClassComponent v1={ 'hello redux'} /> <button onClick={ ()=>{ console.log(store.getState())}}>getState</button> </div>, document.getElementById('example') ); } render() let unsubscribe = store.subscribe(() =>{ render(); console.log(store.getState()); }); //解除监听 // unsubscribe(); </script>
  14. </body>
  15. </html>

参考文档:
Redux 入门教程
Redux入门教程(快速上手)

高阶函数connect

接受四个参数:

  1. connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
mapStateToProps

允许我们将store中的数据作为props绑定到组件上。

  1. const mapStateToProps = (state) => {
  2. return {
  3. count: state.count
  4. }
  5. }
mapDispatchToProps

将action作为props绑定到组件上。

  1. const mapDispatchToProps = (dispatch, ownProps) => {
  2. return {
  3. increase: (...args) => dispatch(actions.increase(...args)),
  4. decrease: (...args) => dispatch(actions.decrease(...args))
  5. }
  6. }
mergeProps

不管是stateProps还是dispatchProps,都需要和ownProps merge 之后才会被赋给MyComp。connect的第三个参数就是用来做这件事。通常情况下,你可以不传这个参数,connect就会使用Object.assign替代该方法。

  1. [mergeProps(stateProps, dispatchProps, ownProps): props]
options

基本上也会用到

发表评论

表情:
评论列表 (有 0 条评论,299人围观)

还没有评论,来说两句吧...

相关阅读

    相关
    redux+react-redux

    本文主要记录下自己在react道路上的爬坑过程 以及对于刚学习redux的同学提供一些可供参考的例子。 要知道redux和react并没有半毛钱的关系,redux甚至可以和j

    相关 react redux

    在react中使用redux入门。 基本的例子使用redux管理react的状态。 <!DOCTYPE html> <html> <head>