无法在上下文中更新状态



在下方编辑

我正试图将我的状态迁移到一些上下文中,这样我就不必不断地支持钻取。问题是,状态不会在上下文中更新。我只想在单击时将状态中的单个值更改为true。

这是我的项目Tile.js

import React, {useContext} from 'react';
import {ProjectContext, ProjectProvider} from './ProjectContext.js';
import {ProjectFunctionsContext, ProjectFunctionsProvider} from './projectFunctionsContext';

// profpic is going to be pulled from the logged in user, for demonstration purposes I just have it pulling the default profile picture right now
import profpic from '../../icon.png';
// projectImage will be passed from the project component, for now it's just a default chosen from the directory.
import defaultProjectImage from '../../defaultProject.jpg';

const ProjectTile = ({projectAuthorName, projectTitle, projectImage,setSavedProjectData}) => {

const [projects, setProjects] = useContext(ProjectContext);
const [projectClicked, setProjectClicked] = useContext(ProjectFunctionsContext);


// Console Log to try to figure out where any errors are coming from, if they arise.
console.log('Project Author: ' + projectAuthorName + " n Project Title: " + projectTitle + " n Project Image: " + projectImage);
// In this return statement, we build the project tile out of the elements that we're getting from the ProjectContext
console.log('projectClicked is doing this: ' + projectClicked);
return (
<div className="ProjectTile__container" onClick={() => {setProjectClicked(true); console.log(projectClicked);setSavedProjectData({projectAuthorName: projectAuthorName})}}>
<img src={defaultProjectImage /*projectImage -- this is commented out because it doesn't work at the moment*/} className="ProjectTile__Img" alt="Placeholder"/>
<div className="ProjectTile__overlay" >
<img src={profpic} className="ProjectTile__icon" alt="Profile"/>
<div className="ProjectTile__text">
{projectTitle}  
<br></br>
{projectAuthorName}
</div>
</div>
</div>
);
}
export default ProjectTile;

这是我的项目FunctionsContext.js

import React, {useState, createContext} from 'react';
export const ProjectFunctionsContext = createContext();
export const ProjectFunctionsProvider = (props) => {
const [projectClicked, setProjectClicked] = useState(false);

return(
<ProjectFunctionsContext.Provider 
value={[projectClicked,setProjectClicked]}
>
{props.children}
</ProjectFunctionsContext.Provider>
);
}

它只是不会更新项目点击为真,我做错了什么?

EDIT:调用该组件父级中的上下文,使其重置状态。它恰好只使用一个调用来获取这些变量。

您需要在ContextProvider中设置values对象,该对象允许您使用useContext挂钩访问组件中的属性。

您的提供商应该是这样的:

const contextValue = {
projectClicked,
setProjectClicked
};
<ProjectFunctionsContext.Provider value={contextValue}>
{props.children}
</ProjectFunctionsContext.Provider>

然后在您的组件中使用useContext钩子来检索存储在context:中的值

const { projectClicked, setProjectClicked } = useContext(ProjectFunctionsContext);