React-Redux的基本使用

React-Redux的基本使用:

由于使用了React-Redux中的connect,不用再关注react的再次渲染,所以不需要写以下代码:

store.subscribe(()=>{
  ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    document.getElementById('root')
  )
})

在这里插入图片描述

(1)UI组件的创建:src----components----count----index.jsx

import React, { Component } from 'react'



export default class Count extends Component {
    add = () => {
        const {value} = this.selectedNumber
        // store.dispatch(createIncrementAction(value*1))
        this.props.jia(value*1)
    }
    remove = () => {
    }
    addtwo = () => {
        const {value} = this.selectedNumber
    }
    render() {
        console.log(this.props)
        return (
            <div>
              <h1>当前求和为:{this.props.count}</h1>
              <select ref={(c)=>this.selectedNumber = c}>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
              </select>
              <button onClick={this.add}>+</button>
              <button onClick={this.remove}>-</button>
              <button>当前求和为奇数再加</button>
              <button onClick={this.addtwo}>异步加</button>
            </div>
        )
    }
}

(2)容器组件Count的创建:src----containers----count----index.jsx

// 引入countUI组件
import CountUI from '../../components/count'
// 引入connect用于连接UI组件与redux
import {connect} from 'react-redux'
import store from '../../redux/store'
// 在第二个括号中将UI组件给传进去
// 第一个括号里需要传两个参数
// 这样的做法是<CountUI n={100} />
// store的状态不需要你写store.getstate()
// 他已经把store.getstate()这个返回值传给了state
// 所以只需要把state这个值给了count就可以了
function mapStateToProps (state) {
    return {count:state}
}

function mapDispatchToProps () {
    return {jia:(data)=>{
        console.log(data)
        // 通知redux执行加法
        store.dispatch({type:'increment',data})
    }}
}

const CountContainer = connect(mapStateToProps,mapDispatchToProps)(CountUI)
// a函数的返回值作为状态传递给了UI组件


export default CountContainer

在app.js中以传props的方式:

import CountContainer from './containers/count'
import store from './redux/store'
function App() {
  return (
    <div>
      <CountContainer store={store}/>
    </div>
  );
}

export default App;

容器组件中mapStateToProps,mapDispatchToProps的一般写法与优化写法:

在这里插入图片描述

如果有多个容器组件的时候,不用给每个容器组件标签传store,只需要在入口index.js文件中引入Provider,如下述代码所示:

import {Provider} from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Realistic-er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值