当我提交新笔记时,我需要重新加载页面才能看到新添加的数据.当我单击提交按钮时,我的控制台日志(log)中显示的唯一错误是这Warning: Each child in a list should have a unique "key" prop.
我正在try 理解useContext和useReducer挂钩.为了更好地理解代码,我只将代码保存在两个文件中.
如何在不重新加载页面的情况下查看新添加的备注,以及如何消除错误?
App.js:
import { useContext, useEffect, useState } from "react";
import { NoteProvider, NotesContext } from "./NoteContext";
export default function App() {
return (
<NoteProvider>
<NotesList />
<AddNewNote />
</NoteProvider>
);
}
function NotesList() {
const { state, dispatch } = useContext(NotesContext);
useEffect(() => {
const getData = async () => {
const res = await fetch("/api/note", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const { data } = await res.json();
console.log("data: ", data);
dispatch({ type: "GET_NOTES", payload: { notes: data } });
};
getData();
}, [dispatch]);
return (
<div>
{state.notes.map((note) => {
return (
<div key={note._id}>
<div>{note.title}</div>
</div>
);
})}
</div>
);
}
function AddNewNote() {
const { state, dispatch } = useContext(NotesContext);
const [note, setNote] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
const res = await fetch("/api/note", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: note }),
});
const data = await res.json()
dispatch({ type: "ADD_A_NEW_NOTE", payload: { notes: data } });
};
const onChange = (e) => {
setNote(e.target.value);
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>Note: </label>
<input className="border" type="text" name="note" onChange={onChange} />
<button className="border" type="submit">
Submit
</button>
</form>
</div>
);
}
NoteConext.js:
import { createContext, useContext, useReducer } from "react";
export const NotesContext = createContext({
notes: [],
});
export default function NotesReducer(state, action) {
const actionPayload = action.payload;
switch (action.type) {
case "GET_NOTES":
return {
...state,
notes: actionPayload.notes,
};
case "ADD_A_NEW_NOTE":
return {
...state,
notes: [...state.notes, actionPayload]
}
default:
return state;
}
}
export function NoteProvider({ children }) {
const initialState = useContext(NotesContext);
const [state, dispatch] = useReducer(NotesReducer, initialState);
return (
<NotesContext.Provider value={{ state, dispatch }}>
{children}
</NotesContext.Provider>
);
}