2,189   Reactjs Redux

一,背景

 

Reactjs 主要负责 Presentational Components 展示,简单的数据处理可以通过 state 和 props 就能完成;
复杂的组件数据处理,建议还是使用 Redux ,目前已经有完善的插件 react-redux 使用方案了;

二,简介:

 

react-redux 通过 Container Components 来管理数据和业务逻辑,利用 Reactjs 的 context 和 props 特性关联 Presentational Components
具体流程:
1,在根节点通过 Provider 组件,将 Redux 的 store 的传给所有的 Container Components 组件
2,每个 Container Components 利用 connect 方法, 将 store 的属性值 state 以及修改数据触发方法 dispatch 传递给 Presentational Components 组件

 

 

代码解释:

1,在根节点,让所有 Container Components 获取 Redux 的 store

 

import { Provider } from 'react-redux'
import configureStore from '../store/configureStore';

const store = configureStore()

export default class Root extends React.Component {
	render(){
		return (
			
				
			
		)
	}
}

 

2,创建 Container Components 并将属性和方法传给 Presentational Components

import { connect } from 'react-redux'
import { clearUser } from '../store/actions'
import head from '../component/head'

// 传递 state 属性值
const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}


// 传递修改 store 的触发 dispatch 方法
const mapDispatchToProps = (dispatch) => {
  return {
    clearUser: () => {
      dispatch(clearUser())
    }
  }
}

// 创建 Container Components ,关联 Presentational Components
const Header = connect(
  mapStateToProps,
  mapDispatchToProps
)(head)

export default Header

 

 

在 Presentational Components 的 this.props 中就可以获取到 store 属性和修改数据的触发 dispatch 方法

const user = this.props.user

this.props.clearUser()

当 Redux 的 store 的数据变化时,react-redux 会自动更新数据到 this.props,从而触发 Reactjs 的 Presentational Components 进行更新




Leave a Reply

Your email address will not be published. Required fields are marked *