我试图以最简单的方式设置 useContext
,但它一直返回 undefined
。
我已经检查了好几次,但仍然无法破译我遗漏的内容。
上下文.js
:
import React from 'react';
export const Context = React.createContext();
export function Provider(props) {
const sayHi = () => {
console.log('hi')
}
const value = {
actions: {
sayHi
}
}
return(
<Context.Provider value={value}>
{props.children}
</Context.Provider>
);
}
消费者组件(Transfer.js
):
import React, { useContext } from 'react';
import { Context } from '../Context';
function Transfer() {
const value = useContext(Context);
console.log(value); // ------> returns undefined
console.log(Context); // ----> it is defined
return (
<div className="send">
// some HTML
</div>
);
}
export default Transfer;
文件夹结构
:
src
└───components
│ └─── Transfer.js
│
└───App.js
└───App.scss
└───Context.js
...
最佳答案
答案:根组件上缺少 Provider
关于javascript - 上下文返回未定义 - useContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67534318/