我在遵循this tutorial时遇到此错误。到目前为止,我完全遵循了他的代码,但是他没有收到此错误。我在本教程中的2:09:30。
我仔细检查了所有挂钩,所有变量和类型似乎都是正确的。我认为setSelectedProject()
可能是一个错误,但是这一调查工作并未取得成果。 allProjects
和projects
肯定是数组...
IndividualProject.js
export const IndividualProject = ({ project }) => {
const [showConfirm, setShowConfirm] = useState(false);
const [projects, setProjects] = useProjectsValue();
const { setSelectedProject } = useSelectedProjectValue();
console.log("Projects: ", projects);
const deleteProject = docId => {
firebase
.firestore()
.collection("projects")
.doc(docId)
.delete()
.then(() => {
setProjects([...projects]);
console.log("Projects from IndividualProject: ", project);
setSelectedProject("Inbox");
});
};
...
src / hooks / Index.js
export const useProjects = () => {
const [projects, setProjects] = useState([]);
useEffect(() => {
firebase
.firestore()
.collection("projects")
.where("userId", "==", "PO1n5mxjYYpcnq9joPZl")
.orderBy("projectId")
.get()
.then(snapshot => {
const allProjects = snapshot.docs.map(project => ({
...project.data(),
docId: project.id
}));
console.log(typeof allProjects);
if (JSON.stringify(allProjects) !== JSON.stringify(projects)) {
setProjects(allProjects);
}
});
}, [projects]);
return { projects, setProjects };
};
Projects.js
export const Projects = ({ activeValue = null }) => {
const [active, setActive] = useState(activeValue);
const { setSelectedProject } = useSelectedProjectValue();
const { projects } = useProjectsValue();
return (
projects &&
projects.map(project => (
<li
key={project.projectId}
data-doc-id={project.docId}
data-testid="project-action"
className={
active === project.projectId
? "active sidebar__project"
: "sidebar__project"
}
onClick={() => {
setActive(project.projectId);
setSelectedProject(project.projectId);
}}
>
<IndividualProject project={project} />
</li>
))
);
};
Here是编译时输出的错误的完整屏幕截图。
答案 0 :(得分:1)
在IndividualProject
自定义钩子的useSelectedProjectValue
组件中使用返回值的方式是错误的:
const [projects, setProjects] = useProjectsValue();
应该是
const { projects, setProjects } = useProjectsValue();
React使用array destructuring e。 G。它们的useState
,但是您的useSelectedProjectValue
钩子返回的是对象而不是数组,因此您必须在具有对象解构的组件中使用它。或将自定义钩子的返回值更改为数组。
如果您想了解更多有关此主题的信息,建议阅读Kent C. Dodds'博客:https://kentcdodds.com/blog/react-hooks-array-destructuring-fundamentals