要想全局使用reducer的数据状态(useContext、useReducer),必须要保证组件在包裹内
,和react-redux的Provider一致
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Store from './store'
import App from './App'
ReactDOM.render(
<Store>
<App />
</Store>,
document.getElementById('root')
);
// store.js
import React, { useEffect } from 'react';
import Reducer from './reducer'
export const AppContext = React.createContext()
function Store(props){
const { book, dispatch } = Reducer()
console.log(book)
console.log(dispatch)
useEffect(()=>{
dispatch({
type: 'save',
name: '六级'
})
dispatch({
type: 'add',
count: 666
})
},[])
return (
<AppContext.Provider value={{book,dispatch}}>
{props.children}
</AppContext.Provider>
)
}
export default Store
// reducer.js
import {useReducer} from 'react';
function Reducer (){
const [book,dispatch] = useReducer((state,action)=>{
switch(action.type){
case 'add':
state.count = action.count
break;
case 'save':
state.name = action.name
break;
default:
break;
}
return {...state}
},{
list: [],
count: 1
})
return { book, dispatch }
}
export default Reducer
// 在其他的组件中也能获取到全局数据
// other.js
import React, { useContext } from 'react';
import { AppContext } from '../store'
function Other(){
const GlobalContext = useContext(AppContext)
console.log(GlobalContext)
return (
<>
<h1>Other Page</h1>
</>
)
}
export default Other