reactjs - 如何使用 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, () => { }]);
解决方案
发生这种情况是因为你的组件在 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')
);
推荐阅读
- python - 尝试抓取任何地方或餐厅的谷歌首页地址但不走运
- wpf - 根据屏幕分辨率自动调整 Windows 应用程序屏幕大小
- c# - 为什么我的 do-while 循环中的 continue 关键字不起作用?
- spring - 将缺少的 URI 变量映射到请求映射
- python - 哪个是再训练 YOLO 神经网络的可取策略?
- python-3.x - django.core.exceptions.ImproperlyConfigured:应用程序标签不是唯一的,重复:帐户
- maven - 如何在构建期间要求 IntelliJ 强制下载 maven 依赖项?
- azure - 无法在 SSDT Visual Studio 2017 中导入 SSIS 包
- redis - Redis 集群在主从之间执行频繁故障转移
- python - FFmpeg 安装需要在 Mac 上卸载 python