1.基础操作
- 在src中
store/index.js文件中
import {createStore } from 'redux'
let initial = {
supNum: 10,
oppNum: 5
}
const reducer = function reducer(state = initial, action) {
state = {...state}
switch (action.type) {
case 'VOTE_SUP':
state.supNum++
break
case 'VOTE_OPP':
state.oppNum++
break
default
}
return state
}
const store = createStore(reducer)
export default store
- 在src中建立上下文对象
ThemeContext.js文件
import React from 'react'
const ThemeContext = React.createContext()
export default ThemeContext
- 在入口index.jsx中通过上下文对象获取store,将store放在祖先上下文中
import store form './store'
import ThemeContext from './ThemeContext'
//...省略很多代码
<ThemeContext.Provider value={{store}}>
<Vote/>
</ThemeContext.Provider>
//...省略很多代码
- 在各个组件中就可以拿到store了,这里以函数组件为例,用useContext函数
import React,{useContext,useState,useEffect} from 'react'
import ThemeContext from '../ThemeContext'
//...
const Vote = function Vote() {
const {store} = useContext(ThemeContext) // 这里就拿到了store了
let {supNum, oppNum} = store.getState(0)
let [num, setNum] = useState()
const update = () => {
setNum(num + 1)
}
useEffect(()=>{
let unsubscribe = store.subscribe(update)//会返回一个方法用来移除
return () => {
unsubscribe()//把上一次的移除释放
}
},[])
return <div>
<p>{supNum + oppNum}</p>
</div>
}
- 在各个组件中就可以拿到store了,这里以类组件为例
import React from 'react'
import ThemeContext from '../ThemeContext'
class Vote extends React.Component {
static contextType = ThemeContext
componentDidMount() {
const {store} = this.context
store.subscribe(() => {
this.forceUpdate()
})
}
render () {
const {store} = this.context // 这里就拿到了store了
return <Button onClick={() => {
store.dispatch({
type: 'VOTE_OPP'
})
}}></Button>
}
}