useReducer+useContext = 全局状态管理 类似于vuex,
-
这样的意义是将所有组件的状态都挂载到外部,即组件内是无状态的。
-
举个栗子useReducer
import React, { useReducer } from 'react' // 1. 引入useReducer
// 2. useReducer需要传入两个参数,reducer和intialState
/**
* reducer 是一个函数 负责处理修改全局中的状态,当组件内调用dispatch 会触发reducer函数 即通知修改状态
* 主要作用:修改状态 拿到旧的状态 衍生出新状态。
* reducer 有两个参数:
* 第一个参数可以拿到上一次的全局状态,
* 第二个参数是一个标识,是可以拿到组件中调用dispatch的参数,根据传过来的消息更改想要更改的状态
*/
/**
* intialState 是一个对象,存放全局状态的初始值
*/
const reducer = (oldState, action)=> {
let newState = {...oldState}
let map = [
[
()=> action.type === 'h-minus',
()=> {
newState.count--
return newState
}
],
[
()=> action.type === 'h-add',
()=> {
newState.count++
return newState
}
]
]
let res = map.find(item => item[0]());
if(res) {
return res[1]()
}else {
}
}
const intialState = {
count: 0
}
export default function App() {
/** useReducer需要传递两个参数,第一个参数是处理函数,第二个是初始化状态对象,会返回一个数组 0:全局状态 1:通知reducer 处理状态*/
const [state, dispatch] = useReducer(reducer, intialState)
return (
<div>
<button onClick={()=> {
dispatch({
type: 'h-minus'
})
}}>-</button>
{ state.count }
<button onClick={()=> {
dispatch({
type: 'h-add'
})
}}>+</button>
</div>
)
}
- 举个栗子useReducer+useContext
import React, { Component, useContext, useEffect, useReducer, useState } from 'react'
import axios from 'axios';
import './css/communinaion.scss'
const GlobalContext = React.createContext() // 创建供应商
// window.GlobalContext = GlobalContext;
const FilmItem = ({ name, poster, grade, synopsis })=> {
const { state, dispatch } = useContext(GlobalContext) // 接收供应商提供的数据
return (
<div className='filmitem' onClick={(e)=> {
dispatch({
type: 'change-con',
value: synopsis
})
}}>
<img src={poster} alt={name}></img>
<h4>{name}</h4>
<div>观众评分:{grade}</div>
</div>
)
}
const FilmDetail = ()=> {
const { state, dispatch } = useContext(GlobalContext) // 接收供应商提供的数据 state: 全局状态 dispatch处理状态
return <div className='filmdetail'>{state.con}</div>
}
const initData = {
con: '',
filmList: []
};
const reducer = (oldState, action)=> {
switch(action.type) {
case "change-filmlist":
return {...oldState, filmList: action.value }
case "change-con":
console.log('change-con:', oldState, action );
return {...oldState, con: action.value}
default: return oldState
}
}
export default function App() {
const [ state, dispatch ] = useReducer(reducer, initData);
const getData = ()=> {
return async()=> {
let { data: { data: { films } } } = await axios({ url: "/test.json", method: "get" });
console.log( films );
dispatch({
type: 'change-filmlist',
value: films
})
}
}
useEffect(()=> {
getData()();
}, [])
return (
// 供应商
<GlobalContext.Provider value={{
state,
dispatch
}}>
<div>
{
state.filmList.map(item => <FilmItem key={item.filmId} {...item}></FilmItem>)
}
{ state.filmList.length === 0 && '空空如也'}
<FilmDetail></FilmDetail>
</div>
</GlobalContext.Provider>
)
}
标签:return,reducer,useReducer,dispatch,state,useContext,const
From: https://www.cnblogs.com/bingquan1/p/16946107.html