Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 无法使用React useContext和UseMoom获取更新状态_Reactjs - Fatal编程技术网

Reactjs 无法使用React useContext和UseMoom获取更新状态

Reactjs 无法使用React useContext和UseMoom获取更新状态,reactjs,Reactjs,我想使用React的useContext和UseMoom来获取更新的值,但是返回的值没有从initialState更新 我写这篇文章的方式有问题吗 下面可以找到一个简单的代码沙盒 /context/AppContext.js import React, { createContext, useCallback, useContext, useMemo, useReducer } from "react"; export const AppContext

我想使用React的useContext和UseMoom来获取更新的值,但是返回的值没有从initialState更新

我写这篇文章的方式有问题吗

下面可以找到一个简单的代码沙盒

/context/AppContext.js

import React, {
  createContext,
  useCallback,
  useContext,
  useMemo,
  useReducer
} from "react";

export const AppContext = createContext();

export const useAppContext = () => {
  return useContext(AppContext);
};

const initialState = {
  bar: null
};

const SET_APP = "SET_APP";

export const reducer = (state, { type, payload }) => {
  switch (type) {
    case SET_APP:
      const { bar } = payload;
      return {
        ...state,
        bar
      };
    default:
      throw Error(
        `Unexpected action type in ElectionContext reducer: '${type}'.`
      );
  }
};

const AppContextProvider = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const appSetter = useCallback(() => {
    dispatch({ type: SET_APP, payload: { bar: "bar" } });
  }, []);

  return (
    <AppContext.Provider
      value={useMemo(
        () => [
          state,
          {
            appSetter
          }
        ],
        [appSetter]
      )}
    >
      {props.children}
    </AppContext.Provider>
  );
};

export const useAppSetter = () => {
  const [, { appSetter }] = useAppContext();
  return appSetter;
};

export const useAppObj = () => {
  const [state] = useAppContext();
  return state;
};

export default AppContextProvider;
import "./styles.css";
import { useEffect } from "react";
import { useAppSetter, useAppObj } from "./contexts/AppContext";

export default function App() {
  const appSetter = useAppSetter();
  const { bar } = useAppObj();

  useEffect(() => {
    appSetter();
  });

  const foo = () => {
    console.log(bar);
  };

  return (
    <div className="App">
      <button onClick={foo}>console</button>
    </div>
  );
}

你忘了添加代码沙盒链接对不起,我只是用代码和链接编辑了这篇文章。