store.js
import { createStore,combineReducers,applyMiddleware } from "redux";
import thunk from 'redux-thunk';
//拆分reducer
//城市reducer
const cityReducer = (pre = {
cityName:'北京'
},action)=>{
const newState = {...pre}
switch(action.type){
case 'cxk':
newState.cityName = action.value
return newState
default:
return pre
}
}
//tab reducer
const tabReducer = (pre = {
show:false
},action)=>{
const newState = {...pre}
switch(action.type){
case 'yes':
newState.name = true
return newState
case 'yes':
newState.name = false
return newState
default:
return pre
}
}
//获取数据
const listReducer = (pre = {
list:[]
},action)=>{
console.log(action)
const newState = {...pre}
switch(action.type){
case 'list':
newState.list = action.value
return newState
default:
return pre
}
}
const reducer = combineReducers({ //合并两个reducer
cityReducer,
tabReducer,
listReducer
})
const store = createStore(reducer,applyMiddleware(thunk)); //创建一个store
export default store
实际使用
const [arr,setArr] = useState([])
const getList = ()=>{ //返回一个函数
return (dispatch)=>{
setTimeout(()=>{
dispatch({
type:'list',
value:[2,3,4,5,6,4,3]
})
},500)
}
}
useEffect(()=>{
const unsubscribe = store.subscribe(()=>{ 发布订阅
setArr(store.getState().listReducer.list)
})
return { //取消订阅
unsubscribe
}
},[arr])
const btnAsync = ()=>{
store.dispatch(getList())
}
<button onClick={btnAsync}>dispatch异步</button>
{
arr && arr.map((item,index)=>(
<div key={index}>{item}</div>
))
}