redux的使用(逐渐完善、非hook)

redux使用示例(逐渐完善、非hook)

不用 redux

// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/app'

ReactDOM.render(<App/>, document.getElementById('root'))
// components/app.jsx
import React, {Component} from 'react'

export default class App extends Component {
  state = {
    count: 0
  }

	// 4个方法
  increment = () => {
    const num = this.refs.numSelect.value*1
    const count = this.state.count + num
    this.setState({count})
  }
  decrement = () => {
    const num = this.refs.numSelect.value*1
    const count = this.state.count - num
    this.setState({count})
  }
  incrementIfOdd = () => {
    let count = this.state.count
    if(count%2==1) {
      const num = this.refs.numSelect.value*1
      count += num
      this.setState({count})
    }
  }
  incrementAsync = () => {
    setTimeout(() => {
      const num = this.refs.numSelect.value*1
      const count = this.state.count + num
      this.setState({count})
    }, 1000)
  }

  render () {
    return (
      <div>
        <p>
          click {this.state} times {' '}
        </p>
        <select ref="numSelect">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>{' '}
        <button onClick={this.increment}>+</button>{' '}
        <button onClick={this.decrement}>-</button>{' '}
        <button onClick={this.incrementIfOdd}>increment if odd</button>{' '}
        <button onClick={this.incrementAsync}>increment async</button>
      </div>
    )
  }
}

使用 redux

文件目录结构:*表示文件夹
src
	*components
  	app.jsx
	*redux
		action-types.js
		actions.js
		reducers.js
		store.js
	index.js
// index.js
import React from 'react'
import ReactDOM from 'react-dom'

import App from './components/app'
import store from './redux/store'

// 定义渲染根组件标签的函数,抽成函数,方便下面的复用
const render = () => {
  ReactDOM.render(<App store={store}/>, document.getElementById('root')) // 传入store
}
// 初始化渲染
render()

// 注册(订阅)监听, 一旦状态发生改变, 自动重新渲染
store.subscribe(render)
// components/app.jsx
/*
应用组件
 */
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import * as actions from '../redux/actions'

export default class App extends Component {
  static propTypes = {
    store: PropTypes.object.isRequired,
  }
	
	/* 4个方法 */
  increment = () => {
    const number = this.refs.numSelect.value * 1
    this.props.store.dispatch(actions.increment(number)) // 调用store的方法更新状态
  }
  decrement = () => {
    const number = this.refs.numSelect.value * 1
    this.props.store.dispatch(actions.decrement(number)) // 调用store的方法更新状态
  }
  incrementIfOdd = () => {
    const number = this.refs.numSelect.value * 1
    let count = this.props.store.getState()
    if (count % 2 === 1) {
      this.props.store.dispatch(actions.increment(number)) // 调用store的方法更新状态
    }
  }
  incrementAsync = () => {
    const number = this.refs.numSelect.value * 1
    setTimeout(() => {
      this.props.store.dispatch(actions.increment(number)) // 调用store的方法更新状态
    }, 1000)
  }

  render() {
    const count = this.props.store.getState() // <App store={store}/> 传入了 store
    
    return (
      <div>
        <p>
          click {this.props.store.getState()} times {' '}
        </p>
        <select ref="numSelect">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>{' '}
        <button onClick={this.increment}>+</button>
        {' '}
        <button onClick={this.decrement}>-</button>
        {' '}
        <button onClick={this.incrementIfOdd}>increment if odd</button>
        {' '}
        <button onClick={this.incrementAsync}>increment async</button>
      </div>
    )
  }
}
// redux/action-type.js
/*
Action对象的type常量名称模块
 */
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
// redux/actions.js
/*
action creator模块
 */
import {INCREMENT, DECREMENT} from './action-types'

export const increment = number => ({type: INCREMENT, number})
export const decrement = number => ({type: DECREMENT, number})
// redux/reducers.js
/*
根据老的state和指定action, 处理返回一个新的state
 */
import {INCREMENT, DECREMENT} from './action-types'

export function counter(state = 0, action) {
  switch (action.type) {
    case INCREMENT:
      return state + action.number
    case DECREMENT:
      return state - action.number
    default:
      return state
  }
}
// redux/store.js
import {createStore} from 'redux'
import {counter} from './reducers'

// 生成一个store对象
const store = createStore(counter) // 内部会第一次调用reducer函数得到初始state=0

export default store

使用 react-redux

文件目录结构:*表示文件夹
src
	*components
  	counter.jsx
	*containers
		app,jsx
	*redux
		action-types.js
		actions.js
		reducers.js
		store.js
	index.js

上述 redux 的版本中,redux 与 react 组件的代码耦合度太高,编码不够简洁。

redux/action-types.js 不变

redux/actions.js 不变

redux/reducers.js 不变

redux/store.js 不变

// index.js
import React from 'react'
import ReactDOM from 'react-dom'

import {Provider} from 'react-redux' // 导入 Provider

import App from './components/app'
import store from './redux/store'

ReactDOM.render(( 
  // 不再渲染 <App>,使用 <Provider> 包裹
  <Provider store={store}> // 参数也放在 <Provider> 中传递
    <App/>
  </Provider>
), document.getElementById('root'))

/* 不需要再订阅监听
// 注册(订阅)监听, 一旦状态发生改变, 自动重新渲染
store.subscribe(render)
*/
// containers/app.jsx
/*
包含counter组件的容器组件
 */
import React from 'react'
import {connect} from 'react-redux' // 引入连接函数
import {increment, decrement} from '../redux/actions' // 引入action函数

import Counter from '../components/counter' // 将逻辑代码抽出

// 向外暴露连接App组件的包装组件
export default connect(
  state => ({count: state}), 
  {increment, decrement} 
)(Counter)
// count 与 counter.jsx中声明的属性一致
// {increment, decrement} 相当于 {increment: increment, decrement: decrement} 第一个 increment 与 counter.jsx 中声明的属性一致,第二个 increment 与 action 中的方法名一致
// components/counter.jsx
/* 
UI组件: 不包含任何redux API
 */
import React from 'react'
import PropTypes from 'prop-types'

export default class Counter extends React.Component {
	
  // 声明需要的属性
  static propTypes = {
    count: PropTypes.number.isRequired,
    increment: PropTypes.func.isRequired,
    decrement: PropTypes.func.isRequired
  }

	/* 4个方法 */
  increment = () => {
    const number = this.refs.numSelect.value * 1
    this.props.increment(number)
  }
  decrement = () => {
    const number = this.refs.numSelect.value * 1
    this.props.decrement(number)
  }
  incrementIfOdd = () => {
    const number = this.refs.numSelect.value * 1
    let count = this.props.count
    if (count % 2 === 1) {
      this.props.increment(number)
    }
  }
  incrementAsync = () => {
    const number = this.refs.numSelect.value * 1
    setTimeout(() => {
      this.props.increment(number)
    }, 1000)
  }

  render() {
    return (
      <div>
        <p>
          click {this.props.count} times {' '}
        </p>
        <select ref="numSelect">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>{' '}
        <button onClick={this.increment}>+</button>
        {' '}
        <button onClick={this.decrement}>-</button>
        {' '}
        <button onClick={this.incrementIfOdd}>increment if odd</button>
        {' '}
        <button onClick={this.incrementAsync}>increment async</button>
      </div>
    )
  }
}

使用 redux 异步(异步中间件)

其他的不变

// redux/store.js
import ...

// 根据counter函数创建store对象
export default createStore(
  reducers,
  composeWithDevTools(applyMiddleware(thunk)) // 启用异步中间件,否则action中默认只能return一个对象
)
// redux/actions.js
import {INCREMENT, DECREMENT} from './action-types'

// 同步的action返回的是一个对象
// 异步的action返回的是一个函数

export const increment = number => ({type: INCREMENT, number})
export const decrement = number => ({type: DECREMENT, number})

// 异步action creator(返回一个函数)
export const incrementAsync = number => {
  return dispatch => { // 返回的是一个函数
    // 异步代码
    setTimeout(() => {
      dispatch(increment(number)) // 分发action
    }, 1000)
  }
}
// containers/app.jsx (就增加了incrementAsync的引入和使用)
import ...

// 向外暴露连接App组件的包装组件
export default connect(
  state => ({count: state.counter}),
  {increment, decrement, incrementAsync}
)(Counter)
// components/counter.jsx
...就增加了incrementAsync的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值