reactjs - React context API-我如何从 useEffect 钩子中分派一个动作?
问题描述
在这个项目中,我使用React.createContext()方法来管理状态。我可以通过导入Context.Consumer并在类组件(或功能组件)的返回方法中使用此使用者来访问状态数据。见下面的例子:
function App(){
return(
<Consumer>
{value=>{
const {basket} = value;
return <p> { basket.length() } </p>
}
}
</Consumer>
)
}
问题是我想从useEffect 钩子而不是从组件返回中调度一个动作
这就是我想做的:
function App() {
useEffect(() => {
auth.onAuthStateChanged(authUser => {
if(authUser){
dispatch({ //I need to use dispatch methode here!!
type : 'SET_USER',
payload : authUser
})
}
else{
dispatch({ //I need to use dispatch methode here!!
type : 'SET_USER',
payload : null
})
}
})
}, [])
return(...)
}
StateProvider.js:
import React, { Component } from 'react';
const Context = React.createContext();
// 1. Selector
export const getSubtotal = (basket)=> basket?.reduce((amount,item)=> item.price + amount ,0);
// 2. Reducer
const reducer = (state,action)=>{
switch(action.type){
case 'ADD_TO_BASKET' :
return{
basket : [action.payload, ...state.basket],
};
case 'DELETE_FROM_BASKET' :
const index = state.basket.findIndex(item=>item.id === action.payload)
let basketCopie = [...state.basket]
basketCopie.splice(index,1)
return{
basket : basketCopie
};
case 'SET_USER' :
return{
user : action.payload
};
default :
return state
}
}
// 3. Provider Classe
export class Provider extends Component {
state = {
basket : [],
user : null,
dispatch : action=> this.setState(state=> reducer(state,action))
}
render() {
return (
<Context.Provider value={this.state} > {/* the value change after any reducer call*/}
{this.props.children}
</Context.Provider>
);
}
}
// 4. Consumer
export const Consumer = Context.Consumer;
解决方案
推荐阅读
- sql - 如何从 2 个不同的表中选择一个共同属性,其中一个共同属性的出现率最高?
- firebase - 当 http firebase-functions 在模拟器下运行和部署时,有没有办法规范 request.url 的差异
- arrays - Kotlin 数组初始化中的 init 调用顺序
- python - 如何解决以前工作的fancyimpute的“ImportError:DLL加载失败:”
- vuejs2 - 如果为空 vuejs2 v-for,如何显示引导警报?
- java - AsyncTask 的 onPostExecute() 方法可以有多个参数吗?
- postgresql - PostgreSQL 插入案例
- traefik - Traefik 中每个服务器的断路器
- c++ - 问题 - 返回文本文件排列的递归函数
- reactjs - 如何通过一劳永逸地重新渲染来修复图像闪烁?