编辑如下
我正在尝试将我的状态迁移到一些上下文中,这样我就不必不断地支持训练。问题是,状态不会在上下文中更新。我只想在单击时将状态中的单个值更改为true。
这是我的projecttile.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;
这是我的projectfunctionscontext.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>
);
}
它不会更新为真,我做错了什么?
编辑:调用此组件父级中的上下文,使其重置状态。它只需要一次调用就可以得到这些变量。
1条答案
按热度按时间cig3rfwq1#
您需要在contextprovider中设置values对象,该对象允许您使用usecontext钩子访问组件中的属性。
您的提供商应如下所示:
然后在组件中,使用usecontext钩子检索存储在上下文中的值: