标签: react-context

React Context API 很慢

我正在尝试新的 Context API 和钩子。我创建了一个带有侧边栏(树视图)、页脚和主要内容页面的应用程序。我有一个上下文提供者

const ContextProvider: FunctionComponent = (props) => {

const [selected, setSelected] = useState(undefined);
const [treeNodes, setTreeNodes] = useState([]);

return (
    <MyContext.Provider
        value={{
            actions: {
                setSelected,
                setTreeNodes
            },
            selected,
            treeNodes
        }}
    >
        {props.children}
    </MyContext.Provider>
);
Run Code Online (Sandbox Code Playgroud)

在我的内容组件中,我有一个包含大约 1000 个项目的详细信息列表(Office Fabric UI)。当我单击列表中的项目时,我想在上下文中更新所选项目。这可行,但速度确实很慢。选择列表中的项目大约需要 0.5-1 秒。该列表是虚拟化的。我已经在生产版本中尝试过了。情况好一点,但单击列表时有明显的滞后。页脚正在使用 myContext 来显示有关所选项目的信息。

这是我的组件中的一些代码

const cntx = useContext(MyContext);

const onClick = (item) => {
    cntx.actions.setSelected(item);
};
Run Code Online (Sandbox Code Playgroud)

我使用的上下文错误吗?

我创建了一个示例沙箱来演示。您可以滚动到大约第 100 个索引,然后单击几次以查看它如何变得无响应。

https://codesandbox.io/s/0m4nqxp4m0

这是 Fabric DetailsList 的问题吗?它会重新渲染很多次吗?我相信问题出在“复杂”DatePicker 组件上,但我不明白为什么DetailsList 会被重新渲染?它没有在渲染函数中使用任何上下文属性。我希望只有页脚组件在每次上下文更改时重新渲染

reactjs office-ui-fabric react-context react-hooks

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

使用 Promise 从异步服务中反应 useContext

我想创建一个实际上来自某些异步服务(例如服务器数据)的上下文。

//the async service to bring the context data
export const fetchContextFromAsycnService = () => {
  return  new Promise(resolve => setTimeout(
      () => resolve('Hey, im in the async context and I am the correct value'), 200)
  );
} 

class App extends Component {
  render() {
    let value = 'Im not the correct value';
    fetchContextFromAsycnService().then(x => value = x as string);
    return (
      <AsyncContext.Provider value={value}>
       <SomeComponent />
      </AsyncContext.Provider>
    );
  }
}
//user the value
export const SomeComponent = ( ) => …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-context

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

undefined 不是一个对象(评估 'Context._context') - React Native

我试图用我创建的用户上下文包装我的导航器之一。我之前在其他项目中已经实现了这一点,但我遇到了一个问题。我尝试遵循此解决方案,但似乎与我遇到的问题不同。我不能确切地说出这里出了什么问题。

App.js 代码:

import React, { useContext, useEffect } from "react";
import { View, Text, AsyncStorage, Button } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import HomeScreen from "./src/screens/HomeScreen";
import LoginScreen from "./src/screens/login";
import CalendarScreen from "./src/screens/Calendar";
import SignUpScreen from "./src/screens/signUp";
import { scale, vs } from "react-native-size-matters";
import { createDrawerNavigator } from "@react-navigation/drawer";
import { createMaterialBottomTabNavigator } from "@react-navigation/material-bottom-tabs";
import { Icon } from "react-native-elements";
import UserContext, { UserProvider } from "./src/screens/Context/UserContext";
import { NavigationContainer } …
Run Code Online (Sandbox Code Playgroud)

react-native expo react-context

2
推荐指数
2
解决办法
5130
查看次数

当我增加计数器时,它会增加 2 而不是 1。我正在为此使用反应上下文

这里我调用了一个函数 addItem,其中我增加了购物车的价值

 <CartItem
                key={`cartItem-${item.item_id}`}
                onIncrement={() => addItem(item)}
                onDecrement={() => removeItem(item)}
                onRemove={() => removeItemFromCart(item)}
                data={item}
              />
Run Code Online (Sandbox Code Playgroud)

我的背景是

const addItemHandler = (item, quantity = 1) => {
    dispatch({ type: 'ADD_ITEM', payload: { ...item, quantity } });
  };
Run Code Online (Sandbox Code Playgroud)

和我的reducer,用于在reducer.js中添加项目

export const addItemToCart = (state, action) => {
  const existingCartItemIndex = state.items.findIndex(
    (item) => item.item_id === action.payload.item_id
  );
  if (existingCartItemIndex > -1) {
    const newState = [...state.items];
    newState[existingCartItemIndex].quantity += action.payload.quantity;
    return newState;
  }
  return [...state.items, action.payload];
};
const reducer = (state, action) => { …
Run Code Online (Sandbox Code Playgroud)

reactjs react-context

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

React:无法使用 useContext 挂钩在 app.js 中设置上下文状态

我无法在 app.js 中设置上下文状态,我以某种方式在其中获得空值,但可以在子组件中访问它。

\n

我想在用户访问页面时在 app.js 中设置上下文状态,以便我可以在整个应用程序中使用它,例如根据用户是否登录显示不同的标题

\n

根据请求的沙盒 URL -> https://codesandbox.io/s/quizzical-snyder-2qghj?file=/src/App.js

\n

我正在关注https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react

\n

应用程序.js

\n
// import installed dependencies\nimport React, { useEffect, useContext } from \'react\';\nimport { BrowserRouter as Router, Switch, Route } from \'react-router-dom\';\n\n// import custom contexts\nimport { AuthContext, AuthContextProvider } from \'./contexts/auth/AuthContext\';\n\n// import pages\nimport Homepage from \'./pages/homepage/Homepage\';\n\n// import components\nimport Footer from \'./components/footer/Footer\';\nimport Header from \'./components/header/Header\';\n\nexport default function App() {\n    const [authState, setAuthState] = useContext(AuthContext);\n\n    useEffect(() => {\n        console.log(authState); // prints *{}*\n        console.log(setAuthState); // prints *() …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-context react-hooks

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

React:在 useEffect 中调用上下文函数时防止无限循环

在我的 React 应用程序中,我渲染了不同的<Item>组件实例,我希望它们在上下文中注册/取消注册,具体取决于它们当前是否已安装。

我正在使用两个上下文(ItemContext提供已注册的项目,ItemContextSetters提供注册/取消注册的功能)来执行此操作。

const ItemContext = React.createContext({});
const ItemContextSetters = React.createContext({
  registerItem: (id, data) => undefined,
  unregisterItem: (id) => undefined
});

function ContextController(props) {
  const [items, setItems] = useState({});

  const unregisterItem = useCallback(
    (id) => {
      const itemsUpdate = { ...items };
      delete itemsUpdate[id];
      setItems(itemsUpdate);
    },
    [items]
  );

  const registerItem = useCallback(
    (id, data) => {
      if (items.hasOwnProperty(id) && items[id] === data) {
        return;
      }

      const itemsUpdate = { ...items, [id]: data }; …
Run Code Online (Sandbox Code Playgroud)

reactjs react-context react-hooks usecallback use-effect

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

具有 React Context 的当前用户

我想要一种使用 React Context 获取和获取当前用户的方法(不要将 props 传递给我的所有组件)

我尝试使用 React Context 但不明白如何实现const { currentUser, fetchCurrentUser } = useCurrentUser()文档中的类似内容。

authentication reactjs react-context

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

How to define type in a array of context in react

I have a context:

export const templateContext = createContext({
  isButtonDisable: true,
  setIsButtonDisable: (p: boolean) => {},
  isSubmitReady: <boolean>false,
  setIsSubmitReady: () => {},
  buttonShow: false,
  handleButtonShow: (val: boolean) => {},
  steps:  [] ,
  handleSteps: (val: never) => {},
});
Run Code Online (Sandbox Code Playgroud)

I am not understanding How can I define the type of array in this context. especially the steps array. That array also contains object

typescript reactjs react-context

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

如何在类组件中使用 Context API

我正在做一个非常大的翻译项目。我使用Formspree来处理表单。我也想翻译一下。

这是Formspree给出的代码:

import React, { useContext } from "react";
import { LanguageContext } from "../../../../App";
import './Form.css';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.submitForm = this.submitForm.bind(this);
        this.state = {
            status: ""
        };
    }
    
    render() {
        const { status } = this.state;
        return (
            <form
                onSubmit={this.submitForm}
                action="https://formspree.io/f/********"
                method="POST"
            >
                {/* <!-- add your custom form HTML here --> */}
                <div className="container">
                    <label style={{ color: 'black', fontSize: '18px' }}>Name <span style={{ color: '#f14b4d' }}>(Required)</span>:</label>
                    <input …
Run Code Online (Sandbox Code Playgroud)

reactjs react-context react-class-based-component

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

React Context 不更新值以传递到另一个页面

我正在创建一个电子商务应用程序,Nextjs并希望在页面之间共享数据。我知道我们不能用来props在页面之间传递数据,所以正在研究 React contextapi。这是我第一次使用 React context api。我研究过,发现你应该在nextjs的_app.js页面中添加Provider。但这会在所有页面之间共享数据。另外,我的数据正在getStaticProps应用程序的 slug 页面中检索。我想将此数据放入我的应用程序的结账页面。

这是我创建的上下文:

import { createContext, useState, useContext } from 'react';

const productContext = createContext({} as any);

export const ProductProvider = ({ children }) => {
  const [productData, setProductData] = useState('');
  return <productontext.Provider value={{ productData, setProductData }}>{children}</productContext.Provider>;
};

export const useProduct = () => useContext(productContext);

Run Code Online (Sandbox Code Playgroud)

_app.js

import { ReportProvider } from '../contexts/ReportContext';
export default function CustomApp({ Component, pageProps }) {
  return (
  
            <ReportProvider>
              <Component {...pageProps} />
            </ReportProvider> …
Run Code Online (Sandbox Code Playgroud)

reactjs next.js react-context

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