我正在尝试在全球范围内捕获一些数据,并且看到有关创建自己的钩子的某些信息,但是由于某些原因,它们无法正常工作!我已经创建了上下文文件,并将其导入到我想使用的组件上,但是仍然无法正常工作。
我的用户上下文| context/user.js
const { createContext, useState, useContext } = require("react");
const UserContext = createContext();
export default function UserProvider({ children }) {
const [user, setUser] = useState([]);
return(
<UserContext.Provider
value={{
user,
setUser
}}
>
{ children }
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
const { user, setUser } = context;
return { user, setUser };
}
我要设置状态的组件| components/header/index.js
import React from 'react';
// Component Elements (E.g: Images, sounds, videos).
import Logo from '../../images/logo.png';
// Every style of this component.
import { Container } from './styles';
import { useUser } from '../../context/User';
export default function Header() {
const [user, setUser ] = useUser();
return (
<Container>
<img src={Logo} alt="Logo" />
<nav>
<ul>
<li><a href='/#'>home</a></li>
<li><a href='https://github.com/llgava/hash-search' target="__blank">open source</a></li>
</ul>
</nav>
<p>{user.dsID}</p>
</Container>
)
}