1

新搭建的个人博客,本文地址:React学习笔记6:使用react-redux更好的组织react和redux
好久没有更新,一是最近太忙,二是redux我理解没那么深,从面相对象架构,要转变为函数式编程架构,以至于细节点拿不准,这个最小代码抽了很久才抽出来,而且不能保证理解完全正确,所以也欢迎拍砖。

上一篇笔记,以最小化的代码模拟了redux的核心,actions、reduces如何运行,这篇笔记首先对上面的代码做初略的改造,把store放到组件外面,尽最大可能让组件独立

import React from 'react'
import ReactDom from 'react-dom'
import { createStore } from 'redux'
class Hello extends React.Component {
  constructor(props) {
    super(props)
    this.state = { msg: 'Hello World!' }
    store.subscribe(() => {
      console.log('store_0 has been updated. Latest store state:', store.getState());
      // 更新你的React数据
      this.setState({ msg: store.getState().msg })
    })
  }

  changeLang = () => {
    //this.setState({msg:'您好,世界!'})
    store.dispatch(actions.sendShowChineseMsg())
    setTimeout(() => {
      store.dispatch(actions.sendShowEnglishMsg())
    }, 5000)
  }
  render() {
    return (
      <div>
        <button onClick={this.changeLang}>翻译</button> {this.state.msg}
      </div>
    )
  }
}

const reducer = (state = {}, action) => {
  console.log('reducer init state ', state, ' action ', action);
  switch (action.type) {
    case 'chinese':
      return {
        state,
        msg: '您好,世界!'
      }
    case 'english':
      return {
        state,
        msg: "Hello World!"
      }
    default:
      return state
  }
}

const actions = {
  sendShowChineseMsg: () => ({ type: 'chinese'}),
  sendShowEnglishMsg: () => ({ type: 'english'})
}

const store = createStore(reducer)

ReactDom.render(
  <Hello />,
  document.getElementById('example')
);

可以看到,无论如何store和组件还是融合在一起,这其中主要是state传值,组件需要从store获取值,另一个就是触发actions的click操作,需要dispatch,触发store的subscribe。

react-redux组件就是解决此问题。react-redux把组件外面再包一层,称之为container,container,组件不需要自己从store获得值,container直接传给组件,actions同样一样,都由container传递,这样组件就跟操作props一样,使用数值、函数,保证了组件的独立性。

包这一层就是使用的react-redux提供的connect函数,connect函数原型如下

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

暂且不关注第三第四个参数,第一参数mapStateToProps就是映射到组件内要传递的props,第二个mapDispatchToProps则是映射到组件内actions,connect函数返回一个函数wrapWithConnect(WrappedComponent),该函数唯一参数是传递一个组件,需要被包起来的组件。

//首先安装react-redux组件
npm install --save react-redux

1、为了模拟react-redux工作,首先需要把组件拆分为两个,其中一个Button组件,用来发送消息,另外一个组件就是展示信息

class Hello extends React.Component {
  render() {
    return (
      <span>{this.props.msg}</span>
    )
  }
}
//暂且将onClick放上,该函数是由mapTranslateDispatchToProps传递而来
class Translate extends React.Component {
  render() {
    return (
      <button onClick={this.props.sendMsg}>翻译</button>
    )
  }
}

2、利用connect绑定state到Hello组件,绑定actions到Translate组件

const mapHelloStateToProps = (state, ownProps) => {
  console.log('mapStateToProps', state, ownProps)
  return {
    msg: state.msg ? state.msg : ownProps.msg
  }
}
//该组件只是展示信息,不需要connect actions,故不需要第二个参数
const HelloWorld = connect(mapHelloStateToProps)(Hello)

const mapTranslateDispatchToProps = (dispatch, ownProps) => {
  return {
    sendMsg: () => {
      dispatch(actions.sendShowChineseMsg())
      setTimeout(() => dispatch(actions.sendShowEnglishMsg()), 5000)
    }
  }
}
//该组件需要发送actions msg,不需要state,第一个参数传递null
const TranslateButton  = connect(null, mapTranslateDispatchToProps)(Translate)

3、利用一个顶层组件,把两个组件串联起来

class App extends React.Component {
  render() {
    return (
      <div>
        <TranslateButton />
        <HelloWorld  msg="Hello World!" />
      </div>
    )
  }
}

4、利用react-redux的Provider组件,把store跟App组件连起来

ReactDom.render(
  <Provider store = {store}>
    <App />
  </Provider>,
  document.getElementById('example')
);

修改完毕后运行即可!
5、以下是完整代码,之后要对代码组织结构做一个调整

import React from 'react'
import ReactDom from 'react-dom'
import { createStore } from 'redux'
import {connect,Provider} from 'react-redux'
class Hello extends React.Component {
  render() {
    return (
      <span>{this.props.msg}</span>
    )
  }
}

class Translate extends React.Component {
  render() {
    return (
      <button onClick={this.props.sendMsg}>翻译</button>
    )
  }
}

const reducer = (state = {}, action) => {
  console.log('reducer init state ', state, ' action ', action);
  switch (action.type) {
    case 'chinese':
      return {
        state,
        msg: '您好,世界!'
      }
    case 'english':
      return {
        state,
        msg: "Hello World!"
      }
    default:
      return state
  }
}

const actions = {
  sendShowChineseMsg: () => ({ type: 'chinese' }),
  sendShowEnglishMsg: () => ({ type: 'english' })
}

const mapHelloStateToProps = (state, ownProps) => {
  console.log('mapStateToProps', state, ownProps)
  return {
    msg: state.msg ? state.msg : ownProps.msg
  }
}
const HelloWorld = connect(mapHelloStateToProps)(Hello)

const mapTranslateDispatchToProps = (dispatch, ownProps) => {
  return {
    sendMsg: () => {
      dispatch(actions.sendShowChineseMsg())
      setTimeout(() => dispatch(actions.sendShowEnglishMsg()), 5000)
    }
  }
}
const TranslateButton  = connect(null, mapTranslateDispatchToProps)(Translate)

class App extends React.Component {
  render() {
    return (
      <div>
        <TranslateButton />
        <HelloWorld  msg="Hello World!" />
      </div>
    )
  }
}

const store = createStore(reducer)

ReactDom.render(
  <Provider store = {store}>
    <App />
  </Provider>,
  document.getElementById('example')
);

MStone
334 声望33 粉丝

全栈攻城狮,PHP++GO+前端,长期工作于创业公司!