首页 > 解决方案 > 如何使用 React Hooks [TypeScript] 创建全局状态

问题描述

目前我正在尝试在 React Hooks 中创建一个全局状态,但遇到了一个问题。

我刚刚在 Store.tsx 中创建了一个 Provider 并尝试使用 useContext 来获取其他组件中的状态。但是当我使用 onChange 处理程序输入输入时,没有更新状态?这是怎么来的。

// App.tsx
export const App: FC = () => {
  const [state, dispatch] = useContext(Context);
  console.log(state.todoList);
  const [inputValue, setInputValue] = useState("");
  const getValue = (target: string) => {
    setInputValue(target);
  };

  const addTodo = () => {
    dispatch({ type: "addTodo", payload: inputValue });
    setInputValue("");
  };

  return (
    <>
      <input value={inputValue} onChange={(e) => getValue(e.target.value)} />
      <button onClick={addTodo}>
        Add Todo
      </button>
      <TodoList />
      {state.value}
    </>
  );
};


// Store.tsx
export const Store: FC = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  console.log(state);

  return (
    <Context.Provider value={[state, dispatch]}>
      <App />
    </Context.Provider>
  );
};

export const Context = createContext<[IStateTypes, Dispatch<any>]>([initialState, () => { }]);

链接到 CodeSandbox

标签: reactjstypescriptreact-hooks

解决方案


发生这种情况是因为你的组件在 index.tsx 中定位和初始化,但是你试图将它包装在 store.tsx 中,所以你的上下文是空的,现在你在 index.ts 中的应用程序看起来像:

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

你应该这样写:

ReactDOM.render(
  <React.StrictMode>
    <Context.Provider value={[state, dispatch]}>
      <App />
    </Context.Provider>
  </React.StrictMode>,
  document.getElementById('root')
);


推荐阅读