【问题标题】:React context API- How i can dispatch an action from the useEffect hook?React context API-我如何从 useEffect 钩子中分派一个动作?
【发布时间】:2021-03-11 15:13:40
【问题描述】:

在这个项目中,我使用 React.createContext() 方法来管理状态。 我可以通过导入 Context.Consumer 并在类组件(或功能组件)的 return 方法中使用此消费者来访问状态数据。 请参阅下面的示例:

function App(){

  return(
    <Consumer>
      {value=>{
                const {basket} = value;
                return <p> { basket.length() } </p>
            }
      }
    </Consumer>
  )
}

问题是我想从 useEffect 钩子而不是从组件 return

发送一个动作

这是我想做的:

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;

【问题讨论】:

  • 如果您使用争议者,为什么不使用 redux。还有一件事你不需要导出消费者,你可以导出上下文本身,然后使用 useContext 钩子来获取你想要的值

标签: reactjs dispatch reducers consumer react-context


【解决方案1】:

好的,我知道这不是一个完整的答案,但我找到了一个我认为对您有很大帮助的页面

context api with hooks

它会一步一步地陪伴你,它对我有很大帮助

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2021-01-10
    • 2020-03-07
    • 2020-12-30
    • 2018-04-18
    相关资源
    最近更新 更多