【发布时间】:2020-06-25 14:16:35
【问题描述】:
我需要你的帮助。我正在使用 useContext 和 useReducer 钩子创建一个应用程序,但我遇到了问题。我有一个功能可以从我的数据库中获取所有笔记。我在 useEffect 挂钩中调用了该函数:
import React, { useContext, useEffect } from "react";
import { useTranslation } from "react-i18next";
//Context
import AuthContext from "../../context/auth/authContext";
import NoteContext from '../../context/notes/noteContext';
//Components
import { Row, Col, Container, Button } from "react-bootstrap";
import Canva from '../Canva/Canva';
import Note from '../Note/Note';
const Dashboard = () => {
const { t, i18n } = useTranslation();
const authContext = useContext(AuthContext);
const { authUser, user } = authContext;
const noteContext = useContext(NoteContext);
const { notes, getNotes, addNote } = noteContext;
useEffect(() => {
getNotes();
}, []);
return (
<>
<Container>
<Row>
<Col sm={12} md={10}>
<Button onClick={() => addNote()} type='button' className='mb-2'>
Añadir elemento
</Button>
<Canva>
{notes && (notes.map(note => {
return (
<Note key={note._id} note={note} />
)
}))}
</Canva>
</Col>
</Row>
</Container>
</>
);
};
export default Dashboard;
如果我以这种方式调用该函数,我的状态不会改变:
notes: undefined
但是,如果我在 useEffect 中引入依赖项,我的应用程序就会陷入无限循环。例如:
useEffect(() => {
getNotes();
}, [notes])
//Or:
useEffect(() => {
getNotes()
}, [getNotes])
如何避免死循环?
【问题讨论】:
-
显示 NoteContext 里面的内容
-
@IanVasco 准备就绪
标签: reactjs