我正在使用 React 开发一个 Web 应用程序,并使用上下文 API 来跨不同层次结构的多个组件存储一些信息。我正在 App.js 上存储如下所示的对象:
/*
import Userinfo from './context/Userinfo'
*/
function App() {
const [userinfo, setuserinfo] = useState({id: some_id, username: some_username, profile_picture: some_profile_picture})
/*
*/
}
Run Code Online (Sandbox Code Playgroud)
然后在更深的组件上使用上下文,如下所示:
import Userinfo from '../context/Userinfo';
function Profile() {
const {userinfo, setuserinfo)=useContext(Userinfo);
const infoupdate = () => { //Function to update the userinfo stored by context API
setuserinfo({id: new_id, username: new_username, profile_picture: new_profile_picture})
}
/////////
Run Code Online (Sandbox Code Playgroud)
问题是,如何只更新一对存储的对象?例如,假设我只想更新“id”部分,同时保持其他字段相同。执行此操作的语法是什么?
预先非常感谢!
我在 next.js 应用程序中使用 context Api 和 useReducer 钩子,当使用 contextProvider 调用 useContext 时,它会返回 undifined 。
下面是我的代码 => contextPage=>
import React, { createContext, useReducer, useContext } from 'react';
import * as types from '../constants/userConstants';
// initialized global store
export const quizContext = createContext();
// reducer
const reducer = (state, action) => {
switch (action.type) {
case types.USER_LOGIN_SUCCESS:
return // user
case types.USER_LOGOUT_SUCCESS:
return // clear user
default:
return state;
}
};
const QuizContextProvider = ({ children }) => {
const [state, dispatch] …Run Code Online (Sandbox Code Playgroud) 再会。这是检查 AuthContext 的本地存储中是否已有令牌的最佳方法吗?我使用 useEffect 挂钩来检查令牌是否已存在。我是否应该更改 isAuthenticated 的初始状态,因为它在渲染时始终为 false?我不知道。谢谢
import React, { useState, useContext, useEffect } from "react";
const AuthContext = React.createContext();
export function useAuth() {
return useContext(AuthContext);
}
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setAuthenticated] = useState(false);
const login = () => {
setAuthenticated(true);
};
useEffect(() => {
const token = localStorage.getItem("AuthToken");
if (token) {
setAuthenticated(true);
} else if (token === null) {
setAuthenticated(false);
}
return () => {};
}, []);
return <AuthContext.Provider value={{ isAuthenticated, …Run Code Online (Sandbox Code Playgroud) authentication local-storage reactjs react-context use-effect
我对 React 的 Context API 有疑问。我的 React 编码水平是初学者。
我正在构建一个具有 8 个上下文的应用程序,它们可能会在项目的未来中增加。它们是我的应用程序不同元素的基本 CRUD 上下文,没有太多复杂性。
当我编写应用程序时,我注意到 App.js 中创建了一个嵌套上下文地狱
为了提供更多信息,我将解释该应用程序的一部分。我有一个针对教练、运动员、法庭等的 CRUD 操作的背景。
在/src目录下的文件夹结构中,我有一个/context目录,其中每个实体都有一个单独的文件夹。我们以教练为例。在/src/context/coach目录中我有 3 个文件。coachContext.js、coachReducer.js 和 CoachState.js
coachContext.js 文件的内容:
import { createContext } from "react";
const coachContext = createContext();
export default coachContext;
Run Code Online (Sandbox Code Playgroud)
coachReducer.js 文件的内容:
const coachReducer = (state, action) => {
switch (action.type) {
case "GET_COACHES":
return {
...state,
coaches: action.payload,
};
case "SET_CURRENT_COACH":
return {
...state,
coach: action.payload,
loading: false,
};
default:
return state;
}
};
export …Run Code Online (Sandbox Code Playgroud) 我正在尝试在存储在服务器文件系统中的另一个选项卡中打开 .pdf(我正在使用 Express、React 和 MySQL)。当用户单击“查看”按钮时,displayCV将执行该函数,并打开一个新选项卡,但 .pdf 内容为空白,即使新选项卡显示 .pdf 包含的正确页数。
流程是这样的:
作业项目.jsx
const displayCV = async (e) => {
e.preventDefault();
await displayCurriculum();
};
Run Code Online (Sandbox Code Playgroud)
JobContext.js
const displayCurriculum = async () => {
const { id } = params;
const response = await axios.get(`/api/jobs/${id}/cv`);
// console.log(response);
const file = new Blob([response.data], {
type: "application/pdf",
});
const fileURL = URL.createObjectURL(file);
const pdfWindow = window.open();
pdfWindow.location.href = fileURL;
};
Run Code Online (Sandbox Code Playgroud)
后端看起来像这样:
jobRoutes.js
const express = require("express");
const router = express.Router();
const { displayCurriculum } …Run Code Online (Sandbox Code Playgroud) import React, { useState, createContext, FC } from "react";
import {
InitialInputValues,
InputsInitiaState,
} from "../components/AccountDetails/AccountDetails.type";
export const TestContext = createContext<InputsInitiaState>(InitialInputValues);
const TodoProvider: FC<React.ReactNode> = ({ children }) => {
const [inputs, setInputs] = useState<InputsInitiaState>(InitialInputValues);
return <TestContext.Provider value={inputs}>{children}</TestContext.Provider>;
};
Run Code Online (Sandbox Code Playgroud)
我有以下问题:我创建了上下文,我试图返回子组件以便将上下文传递给应用程序,但 TypeScript 说 TestContext 找不到它的名称空间。我在很多地方进行了研究,所有地方都显示了相同的处理上下文的方式,有人可以看一下并指出我缺少什么,提前感谢。我也会分享一张错误的图片

我一直在阅读有关在 React 中使用 Context 的优点的文章,但我并不相信。我想知道是否有什么我错过了。
Context 提供了一种通过组件树传递数据的方法,而无需在每个级别手动向下传递 props。
在主组件中创建 props 对象并在下属之间传递它有什么麻烦?就像是:
// do this once at top level (I'm assuming [foo, foo_set] and [bar, bar_set] are state variables):
const props = {foo, foo_set, bar, bar_set, thisAndThat, theOther, whatever, etcAndEtc}
// including one component
<MyComponent1 {...props } />
// including another
<MyComponent2 {...props } />
Run Code Online (Sandbox Code Playgroud)
(也许对该对象使用另一个名称而不是 props 更好,因为组件可以具有其他属性。无论如何。)
然后在 MyComponent1 中你可以访问所有你想要的 props,也可以不访问它们。任何一个:
...
const MyComponent1 = (props) => {
...
// here we can use any props we need, props.bar, props.bar_set, …Run Code Online (Sandbox Code Playgroud) 我第一次尝试使用React上下文API将信息从主要组件传递给他的孙组件。
到目前为止没有问题。一切正常。ChildComponent已检索到上下文值。
最后一个期望失败,并且上下文值是一个空对象。所以foo是不确定的
我在这里重新创建了问题:https : //codesandbox.io/embed/x25yop4x5w?fontsize=14
谢谢您的帮助
我正在尝试使用 createContext、useReducer 和 useContext 在 React Native 中实现 Redux 概念。下面是我的代码文件:
商店.tsx
import React, { useReducer, createContext } from "react";
import { View, Text, StyleSheet, Button } from "react-native";
export const myContext = createContext();
export default function Store(props) {
const counter = 0;
const [state, dispatch] = useReducer((state, action) => {
return state + action;
}, counter);
return (
<myContext.Provider value={{ state, dispatch }}>
{props.children}
</myContext.Provider>
);
}
Run Code Online (Sandbox Code Playgroud)
应用程序.tsx
import React, { useState, useContext, useEffect, createContext } from "react";
import { …Run Code Online (Sandbox Code Playgroud) 我正在尝试呈现房间列表,然后获取房间中每个收件人的用户数据,并且由于房间中只能有 2 个用户(您 + 另一个人),因此收件人只是另一个人。
async renderRooms(room, user) {
const recipentId = room.users.filter(id => id != user.id)[0],
recipients = await userService.getOne(recipentId);
console.log(recipients)
return (
<ListGroupItem tag="a" href="#" data-unread="3" action key={room._id} onClick={this.onRoomOpened.bind(this, room._id)}>
<img src={""} />
<div className="details">
<div className="recipient-name"></div>
<div className="last-message">
<MessageCircle className="feather" />
This is an example last message...
</div>
</div>
</ListGroupItem>
);
}
render() {
if(this.props.rooms.length < 1) return <LoadingPage />;
return (
<userContext.Consumer>
{({user}) => {
if(this.state.roomId) return <ActiveRoom id={this.state.roomId} />;
else
return (
<ListGroup className="recipients">
{this.props.rooms.map(room …Run Code Online (Sandbox Code Playgroud) react-context ×10
reactjs ×10
javascript ×3
typescript ×2
async-await ×1
enzyme ×1
express ×1
jestjs ×1
next.js ×1
pdf ×1
react-hooks ×1
react-native ×1
unit-testing ×1
use-effect ×1