我正在做一些需要维护应用程序级别状态(即全局状态)的事情,我正在使用反应钩子useContext和useReducer.
所以我正在做的是单击按钮,我正在设置我的上下文,然后通过在我的App.js.
我知道为什么我要使用我的数据,因为我首先将初始状态设置为 null,这就是为什么当我刷新页面时它再次设置为 null,但我的要求不是在单击按钮后我想将该数据存储为全局状态,以便我可以进一步使用它
但这不应该是我想要使我的数据全局化并且在刷新时它不应该丢失的情况
我的代码
我的上下文文件
import React, { useReducer, createContext } from "react";
const initialstate = {
someData: null
};
const MyContext = createContext({
someData: null,
click_btn: d => {}
});
const MyReducer = (state, action) => {
switch (action.type) {
case "BTNCLICKED":
return {
...state,
someData: action.payload
};
default:
return state;
}
};
const MyProvider = props => {
const [state, dispatch] = useReducer(MyReducer, initialstate);
const click_btn = d => …Run Code Online (Sandbox Code Playgroud) 希望有人能指出我正确的方向。基本上我已经创建了一个使用钩子的反应应用程序,特别是 useContext、useEffect 和 useReducer。我的问题是我似乎无法通过测试来检测相关组件的点击或调度事件。
可以在以下位置找到我的应用程序的精简版本:https : //github.com/atlantisstorm/hooks-testing 测试与 layout.test.js 脚本相关。
我尝试了各种方法,模拟分派、useContext 等的不同方法,但对此并不满意。最新版本。
布局.test.js
import React from 'react';
import { render, fireEvent } from "@testing-library/react";
import Layout from './layout';
import App from './app';
import { Provider, initialState } from './context';
const dispatch = jest.fn();
const spy = jest
.spyOn(React, 'useContext')
.mockImplementation(() => ({
state: initialState,
dispatch: dispatch
}));
describe('Layout component', () => {
it('starts with a count of 0', () => {
const { getByTestId } = render(
<App>
<Provider> …Run Code Online (Sandbox Code Playgroud) 我是这个useContext钩子的新手,并试图找出我做错了什么......没有顶级导入,我的代码如下所示:
所以我的项目的根看起来像这样:
export default function App() {
return (
<div className="App">
<AppProvider>
<Header/>
<Toolbar/>
<Canvas/>
<Imports/>
<Footer/>
</AppProvider>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个名为 AppProvider 的单独文件,其中包含以下内容:
const CanvasItems = createContext();
const UpdateCanvasItems = createContext();
export function useCanvasItems() {
return useContext(CanvasItems)
}
export function useChangeItems() {
return useContext(UpdateCanvasItems)
}
export default function AppProvider({children}) {
const [state, setState] = useState({
imports: [],
images: [],
text: [],
circles: [],
rectangles: [],
draw: [],
})
// function pushes new items in to state object …Run Code Online (Sandbox Code Playgroud) 该Codesandbox目前仅具有移动样式
我目前有一个根据状态呈现的项目列表。
目标:当用户单击模式内的导航按钮时,它会更新上下文中的状态类型。另一个名为 SuggestionList 的组件通过 useContext 使用上下文并呈现设置为新状态的项目。
问题:上下文中的值肯定会被更新,但是使用上下文的 SuggestionList 组件不会根据上下文的状态使用新的项目列表重新呈现。
这似乎是一个常见问题:
新的 React Context API 是否会触发重新渲染?
React Context api - 上下文更改后消费者不会重新渲染
我已经尝试了来自不同帖子的很多建议,但我只是无法弄清楚为什么我的 SuggestionList 组件在上下文中的值更改时没有重新渲染。我希望有人能给我一些见解。
上下文.js
// CONTEXT.JS
import { useState, createContext } from 'react';
export const RenderTypeContext = createContext();
export const RenderTypeProvider = ({ children }) => {
const [type, setType] = useState('suggestion');
const renderControls = {
type,
setType,
};
console.log(type); // logs out the new value, but does not cause a re-render in the …Run Code Online (Sandbox Code Playgroud) I've seen a few questions related to this topic, but none that tackle the issue head-on in a pure way. useContext is a great tool for minimizing prop-drilling and centralizing key data needed across your app; however, it comes at a cost that I'm trying to minimize.
The closest issue to the one I'm describing here was asked two years ago here. The question didn't gain a lot of traction and the only answer basically says call the context …
我尝试导入聊天机器人上下文,以便在编辑中访问当前聊天机器人,但出了点问题。你知道这里可能是什么问题吗?
非常感谢!
这是我的 chatstate.js 的摘录:
// import packages
import React, { useReducer, useContext } from "react";
import axios from "axios";
// import local dependencies
import AuthContext from "../../Context/Auth/authContext";
import ChatbotContext from "../../Context/Chatbot/chatbotContext";
import chatReducer from "./chatReducer";
import ChatContext from "./chatContext";
import { ADD_INPUT_TO_CHAT, SESSION_ID_CREATED } from "./chatTypes";
const ChatState = props => {
// get access to auth token
const authContext = useContext(AuthContext);
const { token } = authContext;
// get access to current chatbot in edit
const chatbotContext …Run Code Online (Sandbox Code Playgroud) 我想在三个页面之间共享数据(这些是 Web 应用程序的核心),但我也有一堆不关心这些数据的博客页面。我看过的所有地方都建议将 Provider 放在_app.tsx文件中。如果我对MyApp提供者的理解正确,如果有人直接访问www.myurl.com/blog/my-blog-1(来自 google),这将导致提供者运行其功能;即使该页面不会调用 useContext
如何只在 Provider 中包装三页而忽略博客页面?
例如:
这是我的_app.tsx样子:
import { AppProps } from 'next/app'
import '../styles/index.css'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
Run Code Online (Sandbox Code Playgroud) useContext 在这里工作正常,屏幕更改之前的 console.log 按预期工作并为我提供用户对象(只需复制/粘贴相关信息以节省您的时间)
import React, { useContext, useState, useEffect } from "react";
import { AuthContext } from "./AuthProvider";
const Routes = () => {
const { user, setUser } = useContext(AuthContext);
const [initializing, setInitializing] = useState(true);
const onAuthStateChanged = (user) => {
setUser(user);
if (initializing) setInitializing(false);
};
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; //unsub @ unmount
}, []);
if (initializing) {
return null;
}
// console.log(user) //we have access to the user obj here w/out issues …Run Code Online (Sandbox Code Playgroud) reactjs react-native firebase-authentication expo use-context
我希望有条件地调用 useContext。这是我的原始代码,它运行正确,但 tslint 失败。
调用useResourceScope的组件- 比如说Component1
import { useEffect } from 'react';
export function useSubscribeListItemStore(
inputResources?: ResourceScope
) {
const resources = inputResources || useResourceScope();
const listItemStore = resources.consume(listItemStoreKey);
useEffect(function subscribeListItemStore() {
// do some logic
}, []);
}
Run Code Online (Sandbox Code Playgroud)
定义useResourceScope的组件- 比如说Component2
import { createContext } from 'preact';
import { useContext } from 'preact/hooks';
export const ResourceScopeContext = createContext<ResourceScope | undefined>(undefined);
export function useResourceScope(): ResourceScope {
const resources = useContext(ResourceScopeContext);
if (!resources) {
throw new Error( …Run Code Online (Sandbox Code Playgroud) 我无法弄清楚为什么我的 useContext 没有在这个函数中被调用:
import { useContext } from "react";
import { MyContext } from "../contexts/MyContext.js";
import axios from "axios";
const baseURL = "...";
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
.
.
.
});
axiosInstance.interceptors.response.use(
(response) => response,
async (error) => {
const { setUser } = useContext(MyContext);
console.log("anything after this line is not running!!!!");
setUser(null)
.
.
.
Run Code Online (Sandbox Code Playgroud)
我的目标是使用拦截器来检查令牌是否有效以及是否清除用户并进行登录。我在其他 React 组件中使用相同的上下文。它在那里工作正常,只是没有在这里运行!知道我做错了什么吗?
reactjs ×10
use-context ×10
react-hooks ×6
javascript ×3
axios ×1
dispatch ×1
expo ×1
next.js ×1
preact ×1
react-native ×1
react-props ×1
react-state ×1
use-effect ×1
use-reducer ×1