小编bil*_*alo的帖子

React context API - 我如何从 useEffect 挂钩分派操作?

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

function App(){

  return(
    <Consumer>
      {value=>{
                const {basket} = value;
                return <p> { basket.length() } </p>
            }
      }
    </Consumer>
  )
}
Run Code Online (Sandbox Code Playgroud)

问题是我想从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
                    })
                }
            })      

    }, []) …
Run Code Online (Sandbox Code Playgroud)

reducers dispatch consumer reactjs react-context

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

consumer ×1

dispatch ×1

react-context ×1

reactjs ×1

reducers ×1