[英]Map function doesn't map tasks in React
I'm currently learning React and I'm creating a to-do part of a MERN app, I made the task object from MongoDB into an array, and I'm trying to use the map function to make the tasks show up on screen .
我的獲取請求有效,該數組顯示在控制台上,但屏幕上沒有顯示任何內容。 當我控制台記錄 sunday.Task 以嘗試獲取更多信息時,它顯示未定義。
I tried to mess around with the map function for two weeks using react docs, mdn javascript docs, different sites, and I have looked at other map questions on here and they don't seem to fit my use case. 如何編輯此 map function 以便任務顯示在屏幕上?
返回前的 JS:
export default function Planner() {
const [setSunday, setSundayTask] = useState({
Task: "",
});
const [ sundays, setSundayEntry] = useState([]);
const navigate = useNavigate();
// These methods will update the state properties.
function updatesetSunday(value) {
return setSundayTask((prev) => {
return { ...prev, ...value };
});
}
// This function will handle the submission.
async function onSubmitSunday(e) {
e.preventDefault();
// When a post request is sent to the create url, we'll add a new record to the database.
const newSunday = { ...setSunday };
await fetch("http://localhost:5000/sunday/add", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newSunday),
})
.catch(error => {
window.alert(error);
return;
});
setSundayTask({ Task: ""});
navigate("/planner");
}
useEffect(() => {
getSundayTask();
}, [sundays]);
async function getSundayTask() {
let sunday = await axios.get('http://localhost:5000/sunday');
console.log(sunday);
setSundayEntry(sunday);
}
const sundaystodos = Object.keys(sundays);
JSX 用於退貨:
<div>
<h1>Tasks:</h1>
{sundaystodos.map((sunday, id) => {
console.log(sunday.Task)
return (
<li key={id}>
{sunday.Task}
</li>
)})}
</div>
讓我們看看 map 位:
const sundaystodos = Object.keys(sundays);
...
{sundaystodos.map((sunday, id) => {
...
})}
Object.key()
返回一個字符串數組。 總是。 星期天sundays
中的值是什么並不重要,只有鍵是字符串。 因此,當您使用map()
時,您的sunday
變量將是一個字符串,而不是帶有 Task 字段的 object,例如{ Task: 'a task' }
。 如果要在原始 object 中獲取值,則應使用該鍵字符串(我將變量從“sunday”重命名為“key”以使其清楚)您需要使用sundays[sunday]
(或sundays[key]
如果你重命名變量)。 例如,要列出任務字段,您需要sundays[sunday].Task
上面的邏輯假設sundays
是 object,例如{ key: value }
,而不是數組。 如果sundays
是一個數組,那么您不能使用Object.keys()
。
另外,我會推薦一些新的命名。 有太多的“星期天”變量。 例如,我建議使用sundaykeys
而不是sundaytodos
和sundaykeys.map(key =>
。此外,我會為 state 變量的“set”版本使用標准命名,例如const [sundays, setSundays]...
和我不會對第一個 state 變量使用“set”變量,而是使用const [sunday, setSunday]...
希望這可以幫助您走上正軌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.