在我使用 TypeScript 的 React 应用程序中,我想为组件创建一个上下文。如果未提供默认值,则会createContext显示错误。我想传递的值之一是setFilters钩子调度程序。我应该如何提供默认值?
另外,我不希望它是可选的,以防止!调用。
export interface ContextProps {
filters: FiltersType;
setFilters: React.Dispatch<React.SetStateAction<FiltersType>>;
}
export const MyContext = React.createContext<ContextProps>({
filters: defaultFilters, // imported from constants holder
setFilters: // <---- What should be here?
});
const FiltersContext: React.FC<IProps> = (props: IProps) => {
const [filters, setFilters] = React.useState<FiltersType>(defaultFilters);
return <MyContext.Provider value={{ filters, setFilters }}>{props.children}</MyContext.Provider>;
};
export default FiltersContext;
Run Code Online (Sandbox Code Playgroud) 所以我在我的 Gatsby 应用程序中使用 React 的上下文 API(基本上是用 React 编写的)来处理用户身份验证。我有两个使用该上下文的组件:dashboard和navBar。当我尝试登录和注销时, my 的navBar行为会根据 my 有所不同userContext,但 mydashboard不会响应。它是否与结构有关,例如navBar是 的直接“子级” layout,但dashboard不是?我认为不是,毕竟,这就是为什么我使用contextAPIthen 只是传递一个普通的道具。
以下是代码:
//layout.js
import React, { useContext, useState, createContext } from "react"
import Navbar from "../components/navBar"
import {monitorAuth} from "../firebase/firebaseService"
export const UserStateContext = createContext(null)
export const SetUserContext = createContext()
const Layout = ({ children }) => {
const [user, setUser] = useState()
console.log(user)
monitorAuth(setUser)// everytime a layout …Run Code Online (Sandbox Code Playgroud) 我已经尝试过一些解决方案,特别是在这个链接上......
我尝试更改 TodosContext.js 文件中的值..这也不起作用..我尝试过的另一件事是从另一个组件调用 useContext() 函数,但这也不起作用..
这是我的代码。应用程序.js:
import React, { useState, useContext } from 'react';
import TodoList from './components/TodoList';
import NewTodo from './components/NewTodo';
import { TodosProvider, TodosContext } from './components/contextapi/TodosContext';
function App() {
const [input, setInput] = useState('');
const [todos, setTodos] = useContext(TodosContext);
const _handleInput = (e) => {
setInput(e.target.value)
}
const _todoAdd = (e) => {
if (e.key === 'Enter') {
setTodos(
[...todos, { content: input, id: Date.now(), completed: false }]
)
setInput('')
}
}
const _todoRemove …Run Code Online (Sandbox Code Playgroud) 好吧,请对我温柔一点,我对 React Native 还很陌生,但我正在使用 Context 来管理我的 React Native 项目中的一些状态。这是我陷入困境的一个例子
在功能组件的顶部我有这个......
import DataContext from "../../contexts/DataContext";
import AsyncStorage from "@react-native-community/async-storage";
const AccountHomepageScreen = ({navigation}) => {
const { data, updateInfo} = useContext(DataContext);
const getUserFromAsync = async () => {
try {
const value = await AsyncStorage.getItem('user_id');
if(value !== null) {
//shows user_id in Alert no problem
alert(value);
//but this does not work?!?!
updateInfo('userId', value);
}
} catch(e) {
// error reading value
return false;
}
}
}
useEffect(() => {
getUserFromAsync();
}, …Run Code Online (Sandbox Code Playgroud) 我在组件中使用多个钩子,并且需要将钩子传递给值。React 文档有点令人困惑,我不太明白如何格式化该信息以便我的其他组件可以使用它。如何将钩子传递给该值,以便其格式正确,以便可以使用。因为我认为我做错了有人能指出我正确的方向吗?
上下文API
import React, { useState, createContext } from 'react';
export const OptionsContext = createContext();
export const OptionsProvider = props => {
const [name, setName] = useState('');
const [price, setPrice] = useState(0);
const [amountOfOptions, setAmountOfOptions] = useState(0);
const [totalAmountSpent, setTotalAmountSpent] = useState(0);
const [listOfOptions, setListOfOptions] = useState([]);
const { clock } = new Date().toLocaleDateString();
return (
<OptionsContext.Provider value={
[name, setName],
[price, setPrice],
[amountOfOptions, setAmountOfOptions],
[totalAmountSpent, setTotalAmountSpent],
[listOfOptions, setListOfOptions],
clock
}>
{ props.children}
</OptionsContext.Provider>
);
}
Passing the API here …Run Code Online (Sandbox Code Playgroud) 我正在开发一个 Web 应用程序,并且正在使用 React Context,而不使用 useReducer() 挂钩。这是我如何在应用程序中使用 Context 的简单示例:
const [stateValue, setStateValue] = useState("");
const [stateValue1, setStateValue1] = useState("");
const contextValue : MainContext = {
stateValue: stateValue,
setStateValue: setStateValue,
stateValue1: stateValue1,
setStateValue1: setStateValue1
}
Run Code Online (Sandbox Code Playgroud)
因此,我将 contextValue 传递给我的 Context Provider,每次子组件必须更改 stateValuex 时,只需调用 setStateValuex,以便它触发所有子组件内 stateValuex 的重新渲染。使用 useReducer() 钩子代替 Context 有什么优点和缺点?
我有反应功能组件MainToolBar。在导航到其他页面(功能组件)时,我需要更改 MainToolBar 的标题。我怎么能这么做呢?使用 Context API 或 Redux 或任何其他简单的东西
以下是 MainToolBar.Js 的代码
export default function MainToolBar() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Typography align="center" variant="h6" className ={classes.title}>
ERP System
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
以下是 Thirdparty.js 的代码
function ThirdParty() {
return (
<div>
<label>ThirdParty</label>
</div>
)
}
export default ThirdParty;
****layout.js****
import {
BrowserRouter as ReactRouter,
Switch as ReactSwitch,
Route as ReactRoute,
} from "react-router-dom";
import ThirdParty from "./ThirdParty.js";
export default function …Run Code Online (Sandbox Code Playgroud) 我在 React 中创建了以下上下文:
import { useBoolean } from "@chakra-ui/react"
import { createContext, FC } from "react"
type useBooleanReturn = ReturnType<typeof useBoolean>
export const MobileContext = createContext<
[show: useBooleanReturn[0], setShow: useBooleanReturn[1]] | undefined
>(undefined)
// --- PROVIDER
const MobileProvider: FC = ({ children }) => {
const [show, setShow] = useBoolean()
return (
<MobileContext.Provider value={[show, setShow]}>
{children}
</MobileContext.Provider>
)
}
export default MobileProvider
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都很好,但是当我尝试使用这个上下文时,结果发现正在传递的是undefined. 也就是说,下面的代码中value是未定义的:
const value = React.useContext(MobileContext)
Run Code Online (Sandbox Code Playgroud)
不过,我不知道为什么会这样,因为我useBoolean在设置上下文时使用了钩子——即这一行: const [show, setShow] = useBoolean() …
我正在用打字稿创建一个上下文。
export const UserContext = createContext<
{ user: User; onChangeUser: (userId: string) => void } | undefined
>(undefined);
Run Code Online (Sandbox Code Playgroud)
创建将子元素收集为 prop 的提供程序时,出现以下错误
export function UserProvider({ children }: Props) {
const [userId, setUserId] = useState<string | null>(null);
// this error: Cannot find namespace 'UserContext'.
return (
<UserContext.Provider
value={{
user,
onChangeUser: (userId: string) => {
setUserData(userId);
},
}}
>
{children}
</UserContext.Provider>
);
}
Run Code Online (Sandbox Code Playgroud) 我有一个上下文,我将其导入到我的功能组件中:
import { TaskContexts } from "../../../contexts";
Run Code Online (Sandbox Code Playgroud)
上下文存储数据和函数。
数据来自上下文并显示在站点上。
const {
editTodo,
setEditID,
toggleTodoCompletion,
editID,
editTodoHandler,
removeTodo,
state,
text,
isEditError,
} = useContext(TaskContexts);
Run Code Online (Sandbox Code Playgroud)
但!
<button onClick={() => editTodo(todo.id)}>
<img src={editIcon} alt="edit button"></img>
</button>
Run Code Online (Sandbox Code Playgroud)
当我尝试调用 editTodo 函数时,它失败并出现以下错误:
Uncaught TypeError: editTodo is not a function
Run Code Online (Sandbox Code Playgroud)
如何修复这个错误?
UPD。
完整组件代码
import React, { useState } from 'react';
import ACTION_TYPES from '../ToDo/reducer/actionTypes';
import RenderedTable from './RenderedTable';
import styles from './TaskList.module.scss';
import allIcon from '../../icons/all.svg';
import completedIcon from '../../icons/completed.svg';
import notCompletedIcon from '../../icons/notCompleted.svg';
import mona from …Run Code Online (Sandbox Code Playgroud) react-context ×10
reactjs ×10
javascript ×3
typescript ×3
react-hooks ×2
material-ui ×1
react-native ×1
react-redux ×1
react-state ×1
render ×1
use-context ×1