简体   繁体   English

在 react js 中使用 Context 和 hook

[英]Using Context and hook in react js

is me againg... 3 hours ago I had a questions about how used context and usestate in react, but I found the answer myself, but now, I'm having anther trouble, is about setState or setcategoria in my case, so this are the component:是我再次... 3小时前我有一个关于如何使用上下文和usestate做出反应的问题,但我自己找到了答案,但现在,我遇到了另一个麻烦,在我的情况下是关于setState或setcategoria,所以这个是组件:

CategoriaState.js分类状态.js

const [ categorias, setCategorias ] = useState(Data);

const AddCategoria = (description, idPadre) => {
    categorias.push({
        id: categorias.length,
        description: description,
        idPadre: idPadre
    });
    console.log(categorias);
    return true;
};

const DelCategoria = (id) => {
    const newData = categorias.filter( item => item.id !== id );  
    setCategorias({ newData });
    return true;
};

return(         
    <CategoriaContext.Provider
                value={{ 
                        categorias: categorias,
                        GetCategorias,
                        AddCategoria,
                        DelCategoria
                }}                 
    >
        {props.children}
    </CategoriaContext.Provider> 
)

the functions GetCategorias, Addcategorias are working so good,:! GetCategorias、Addcategorias 的功能运行良好,:! but the problem is in DelCategoria, this is the error:但问题出在 DelCategoria 中,这是错误:

Uncaught TypeError: categorias.map is not a function

so if I commnet in line setCategorias({ newData });所以如果我在 setCategorias({ newData }); in function DelCategoria, the error is not displayed, but fortunately the variable categoria is not updated, I think the error is there.在function DelCategoria 中,没有显示错误,还好变量categoria 没有更新,我认为错误是有的。

so I call de function DelCategoria from my component AllCat.js所以我从我的组件 AllCat.js 中调用 de function DelCategoria

    .
    .
    .
    const { categorias, GetCategorias, DelCategoria }  = useContext( CategoriaContext );

    useEffect(() => {
        GetCategorias();
    },[])
   .
   .
   .

   <button onClick={ () => DelCategoria(item.id) } >
      Del Item                                    
    </button> 

my intention is created an simple example in react js using context and usestate, I want understand this api(use context)我的意图是使用 context 和 usestate 在 react js 中创建一个简单的示例,我想了解这个 api(使用上下文)

thanks!!谢谢!!

You are setting a categorias property as an object, not an array您将分类属性设置为 object,而不是数组

   setCategorias({ newData });

Just make a setCategorias(newData) instead and I think this should work只需制作一个setCategorias(newData) ,我认为这应该可行

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

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