首先我们得知道react的context的用法:通过在context提供者中添加childContextTypes和getChildContext来添加context,然后在子组件中通过contextTypes来获取参数,通过它我们可以将数据跨组件传送。
以及高阶组件的作用:高阶组件实质上就是一个函数,这个函数接受一个组件作为参数,并返回一个新的组件。

想要实现简单的状态的管理,我们需要一个存储数据的store和一个可以改变这个store内数据的动作。
代码如下:

react
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Provider extends Component {
//选择需要放在context上的数据和方法
static childContextTypes = {
store: PropTypes.object,
setStore: PropTypes.func
}
getChildContext() {
return {
store: this.state.store || {},
setStore: this.setStore
}
}
//通过此方法来修改store内的数据
setStore = (data) => {
this.setState({ store: { ...this.state.store, ...data } })
}
//初始时的数据,如果没有从组件外传入则为空对象
state = {
store: this.props.store || {}
}
render() {
return this.props.children
}
}

const connect = WrapComponent => {
//返回一个新的传入了store与setStore方法的组件
return class connect extends Component {
//通过contextTypes来选择需要使用context内的数据或方法
static contextTypes = {
store: PropTypes.object,
setStore: PropTypes.func
}
render() {
const { store, setStore } = this.context
const props = { ...this.props, store, setStore }
return <WrapComponent {...props}></WrapComponent >
}
}
}

export { Provider, connect }

需要使用时通过在组件树的高层初始化store,然后在需要使用store的子组件外通过此代码导出的connect方法包裹此子组件即可通过组件的props拿到store和setStore。