简体   繁体   English

组件内部的 function 不提供 React 上下文

[英]React context isn't available from function inside component

Hello I have a problem with React Context.您好,我对 React Context 有疑问。 I'm using React-DnD and I'm trying to get context in feed function but it's empty.我正在使用 React-DnD,我试图在feed function 中获取上下文,但它是空的。 In this function I'm getting context default value but outside that function I'm getting correct values and I don't know why.在这个 function 中,我得到了上下文默认值,但在 function 之外,我得到了正确的值,我不知道为什么。

const Dog = () => {
const needsCtx = useContext(NeedsContext);
const invCtx = useContext(InventoryContext);
console.log(invCtx);
const feed = () => {
    console.log(invCtx);

};
needsCtx.saveCurrentContextToDatabase();
const [{ isOver }, drop] = useDrop(
    () => ({
        accept: "food",
        drop: () => feed(),
        collect: (monitor) => ({
            isOver: !!monitor.isOver(),
        }),
    }),
    []
);
return (
    <div className={styles["wrapper-dog"]}>
        <img ref={drop} className={styles.dog} alt="dog" src={dog}></img>
    </div>
);
};

context:语境:

 import React, { useState } from "react";
export const InventoryContext = React.createContext({
    items: {},
    setItems: () => {},
});

const InventoryContextProvider = (props) => {
    const [items, setItems] = useState({});
    return (
        <InventoryContext.Provider value={{ items: items, setItems: setItems }}>
            {props.children}
        </InventoryContext.Provider>
    );
};
export default InventoryContextProvider;

I do not know ReactDnD, but I do love me some DnD, which is why I'm trying to help out.我不知道 ReactDnD,但我确实爱我一些 DnD,这就是我试图提供帮助的原因。 I'm going to make suggestions here, and continue to edit this answer, because it's easier than trying to write it all in comments, and no one else seems to be answering.我将在这里提出建议,并继续编辑此答案,因为这比尝试将其全部写在评论中要容易,而且似乎没有其他人在回答。

So Mods, please don't delete.所以Mods,请不要删除。 When we figure this out, I will format this answer to best represent the answer to the question asked.当我们弄清楚这一点时,我将格式化这个答案以最好地代表所问问题的答案。


<InventoryContext.Provider value={{ items: items, setItems: setItems }}>

This line confuses me most.这条线最让我困惑。 Mostly because, you're using state inside of the Provider, so why do you also need to declare items and setItems inside the context itself?主要是因为您在 Provider 内部使用了 state,那么为什么还需要在上下文本身中声明itemssetItems呢?

Since you're using the state inside the Provider, couldn't you remove the items and setItems inside the context itself, and then just pass as:由于您在提供程序中使用 state ,您不能在上下文本身中删除itemssetItems ,然后传递为:

<InvetoryContext.Provider value={{ items, setItems }}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM