我有一个应用程序,我在其中使用 3 Context Provider。要使应用程序正常工作,我必须将 <App/>所有这些providers. 随着我的应用程序的增长,我希望有更多的提供程序来处理我必须连接的更多类型的数据。我已经开始觉得可能有更好的方法将提供者传递到<App />.
我的App.js代码:
import React from 'react';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import { Provider as BlogProvider} from './src/context/BlogContext';
import { Provider as VehicleProvider} from './src/context/VehicleContext';
import { Provider as AuthProvider} from './src/context/AuthContext';
import IndexScreen from './src/screens/IndexScreen';
import ShowScreen from './src/screens/ShowScreen';
import CreateScreen from './src/screens/CreateScreen';
import EditScreen from './src/screens/EditScreen';
import VehicleScreen from './src/screens/VehicleScreen';
const navigator = createStackNavigator(
{
Index: IndexScreen, …Run Code Online (Sandbox Code Playgroud) 我是 React 新手,我想在我的班级中使用 useContext,我该如何解决这个问题?这是我当前代码的示例
import { Context } from '../context/ChatListContext'
const ChatList = ({ onAction }) => {
const {state, fetchChatList} = useContext(Context)
Run Code Online (Sandbox Code Playgroud)
我对我的班级也有同样的期待
import { Context } from '../context/ChatListContext'
class MainScreen extends Component {
//const {state, fetchChatList} = useContext(Context) *how do i declare this?
constructor(props) {
super(props)
this.state = { loading: true, showAction: false }
setTimeout(() => {
StatusBar.setBackgroundColor(primary)
}, 100)
}
...
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以启发我吗?
我正在寻找在反应中使用全局屏幕加载器的解决方案。
我不太熟悉反应上下文,但我想知道这是否可以帮助我。基本上我正在介绍一个屏幕加载器,我想也许最好的方法是在主要组件中的某个地方有一个全局加载器。所以得出结论:
那么有没有一种方法可以拥有 loader/loaderText 的全局状态,并在需要时使用上下文进行设置和重置?
如果有一种简单的方法可以做到这一点,那么您认为使用这种解决方案可能有任何缺点吗?也许这有点过分了。
我想以正确的方式定义接口,但我遇到了麻烦,因为即使参数为空,它也期待一个参数。
我正在使用useContext并且我定义了这样的接口:
//react-auth0-spa.tsx
interface Auth0Context {
......
loginWithRedirect: () => void; //I know this is the problem but I don't know what to define.
......
}
Run Code Online (Sandbox Code Playgroud)
在提供者中,value是:
//react-auth0-spa.tsx
<Auth0Context.Provider
value=({
....
loginWithRedirect: (...p: string[]) => auth0Client.loginWithRedirect(...p)
....
})
>
Run Code Online (Sandbox Code Playgroud)
现在,我import将上下文放到另一个文件中,如下所示:
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
这就是错误发生的地方
///components/NavBar.tsx
const { isAuthenticated, loginWithRedirect, logout } = useAuth0()
<div>
{!isAuthenticated && (
<button onClick={() => loginWithRedirect({})}>Log in</button> //Expected 0 arguments, but got 1
)} …Run Code Online (Sandbox Code Playgroud) 我正在使用 NextJS 构建一个应用程序。我的应用程序显示帖子列表,用户能够从 AZ 或 ZA 对列表进行排序,并在每页显示特定数量的帖子(10,20 等)。当用户单击帖子访问该特定帖子页面,然后返回主列表时,排序和分页首选项将被重置,我设法使用 cookie 保留保留的值,但我想改用useContext()。对于这个应用程序,我有一个Layout.js文件,并且认为这是插入我的文件的正确位置,Provider如下所示:
import React, {useState} from 'react';
import Navbar from './Navbar';
import Head from 'next/head';
import {SortingContext} from './UseContext';
const Layout = (props)=> {
const [value, setValue] = useState('hello');
return (<SortingContext.Provider value={{value, setValue}}>
<div>
<Head>
<title>MyApp</title>
</Head>
<Navbar/>
{props.children}
</div>
</SortingContext.Provider>
)};
Run Code Online (Sandbox Code Playgroud)
但是当我尝试从我的其中一个页面获取价值时,我得到了TypeError: Cannot read property 'value' of null
我useContext在应用程序的其他地方使用,所以我知道我可以让它工作。我只是不知道将其放在 NextJS 应用程序中的何处,因此即使我访问不同的页面,该值也会保留。
这是我的 index.js,我试图在其中打印值:
import React, { useState, useEffect, useContext } from 'react'; …Run Code Online (Sandbox Code Playgroud) 我有两个组件“父组件”和“子组件”,我想将上下文从“父组件”导出到“子组件”,但这会导致循环依赖。
例如,考虑 Parent.js
import {Child} from './Child.js';
export const MyContext = React.createContext();
const Parent = () => {
return <MyContext.Provider><Child /></MyContext.Provider>;
}
Run Code Online (Sandbox Code Playgroud)
和 Child.js 作为
import {MyContext} from 'Parent';
const Child = () => {
const myContext = useContext(MyContext);
return <>{myContext}</>;
}
Run Code Online (Sandbox Code Playgroud)
我可以将其作为道具传递,但如果有多层嵌套,那就很困难了。我能想到的一个可能的解决方案是使用另一个名为 的文件contexts.js,并从那里导出我的所有上下文。
有一个更好的方法吗?
我是上下文 API 的新手,并试图让我的代码正常工作。我收到错误:
未捕获的类型错误:对象不可迭代(无法读取属性 Symbol(Symbol.iterator))
你们中的一些好人会帮忙解决这个问题吗?
initialUserState 记录一个如下所示的对象:{name: nanny}
我的上下文文件是:
import { createContext, useState } from "react";
const initialUserState = JSON.parse(localStorage.getItem("user"));
console.log(initialUserState);
const initialFormValues = {
video: "Video.mp4",
hourly: "",
ageRange: [],
car: "",
languages: [],
homework: "",
license: "",
preference: "",
vaccination: "",
radius: "",
booked: "",
fileUpload: "file.jpg",
};
export const Global = createContext();
export default function GlobalContext({ children }) {
const [state, setState] = useState(initialUserState);
const [values, setValues] = useState(initialFormValues); //setting form state
const [radioSelected, setRadioSelected] = …Run Code Online (Sandbox Code Playgroud) 我有一个简单的上下文,它设置从后端伪代码获取的一些值:
export const FooContext = createContext();
export function Foo(props) {
const [value, setValue] = useState(null);
useEffect(() => {
axios.get('/api/get-value').then((res) => {
const data = res.data;
setValue(data);
});
}, []);
return (
<FooContext.Provider value={[value]}>
{props.children}
</FooContext.Provider>
);
}
function App() {
return (
<div className="App">
<Foo>
<SomeView />
</Foo>
</div>
);
}
function SomeView() {
const [value] = useContext(FooContext);
console.log('1. value =', value);
const myFunction = () => {
console.log('2. value = ', value);
}
return (<div>SomeView</div>)
Run Code Online (Sandbox Code Playgroud)
有时我会得到:
1. value = …Run Code Online (Sandbox Code Playgroud) 我试图通过并更新状态useContext;
应用程序.js
import Home from './components/Home'
const UserContext = createContext();
function App() {
const [name, setName] = useState('Name');
return (
<UserContext.Provider value={{name, setName}}>
<Home/>
</UserContext.Provider>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
主页.js
import UserContext from '../../App'
function Home() {
const user = useContext(UserContext);
return (
<>
<label>Your name:</label>
<input type='text' onChange={e => user.setName(e.target.value)} />
<p>{user.name}</p>
</>
)
}
export default Home;
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
类型错误:无法读取未定义的属性(读取“名称”);
使用 useContext 在组件之间传递状态的正确方法是如何?
假设我有一个用于检查用户是否登录的基本设置:
import { createContext } from "react";
const UserContext = createContext<string | null>(null)
export default UserContext
Run Code Online (Sandbox Code Playgroud)
在我的 App.tsx 中,我想创建一个 useState 挂钩,以便我可以管理整个应用程序中的上下文状态:
//Context
const [context, setContext] = useState<string | null>(null)
<UserContext.Provider value={{context, setContext}}>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/login" element={<Login/>}/>
<Route path="/register" element={<Register/>}/>
<Route path="/admin" element={<Admin/>}></Route>
</Routes>
</UserContext.Provider>
Run Code Online (Sandbox Code Playgroud)
因此,据我所知,我只需要登录用户的名称,或者如果我想拒绝访问某些页面,则将上下文的状态设置为空。现在的问题是打字稿在这里对我大喊大叫,特别是在 Provider 的值中:
Type '{ context: string | null; setContext:
React.Dispatch<React.SetStateAction<string | null>>; }' is not assignable to type 'string'.ts(2322)
Run Code Online (Sandbox Code Playgroud)
我可以强制转换该值,如下所示:
value={{context, setContext} as any}
Run Code Online (Sandbox Code Playgroud)
但这似乎并不是一个特别优雅的“打字”解决方案。
任何帮助表示赞赏!
use-context ×10
reactjs ×9
react-hooks ×4
javascript ×2
react-native ×2
typescript ×2
frontend ×1
loader ×1
next.js ×1
provider ×1
use-state ×1