[英]Why doesn't localStorage.setItem work outside of componentDidMount?
[英]why setItem aren't letting 'edit button' work?
我正在嘗試借助簡單的鈎子為每個項目設置一個編輯按鈕。 我已經使用map來查看項目的元素......但不知何故它不起作用......按下按鈕時沒有顯示...... Codesandbox鏈接: https://codesandbox.io/s/condescending- worker-s0igh app.js:
import React, { useState } from "react";
import TodoList from "./TodoFiles/TodoList";
const defaultItems = [
{ id: 1, title: "Write React Todo Project", completed: true },
{ id: 2, title: "Upload it to github", completed: false }
];
const App = () => {
const [items,setItems]=useState(defaultItems)
const editItem=({id,title})=>{
setItems(items.map(p=>p.id===id?{...p,title}:p))
}
return (
<div style={{ width: 400 }}>
<hr />
<TodoList
items={items}
editItem={editItem}/>
<hr />
</div>
);
};
export default App;
TodoList.js:
import React from "react";
const TodoItem = ({ title, completed, editItem }) => {
return (
<div style={{ width: 400, height: 25 }}>
<input type="checkbox" checked={completed} />
{title}
<button style={{ float: "right" }} onClick={() => editItem(title)}>
Edit
</button>
</div>
);
};
const TodoList = ({ items = [], index,editItem }) => {
return items.map((p, index) => (
<TodoItem
{...p}
key={p.id}
index={index}
editItem={editItem}
/>
));
};
export default TodoList;
我不想在自定義鈎子中使用 useEffect 或 useReducer ...因為我想練習基礎知識。 很抱歉我的常見問題,我正在努力學習這個 reactjs,我不想放棄...thanx 提前,如果可能的話,你能用純文本解釋,為什么它不起作用。
您忘記將id
傳遞給editItem
組件中按鈕 onClick 上的TodoItem
。
此外,您不應該像這樣在 setState function 中使用舊的 state (在editItem
函數中)。 您應該使用更新程序 function 參數。 感謝您始終修改當前的 state。
const editItem = ({id,title}) => {
setItems(oldItems => (olditems.map(p=>p.id===id?{...p,title}:p)))
}
import React from "react"; const TodoItem = ({id, title, completed, editItem }) => { return ( <div style={{ width: 400, height: 25 }}> <input type="checkbox" checked={completed} /> {title} <button style={{ float: "right" }} onClick={() => editItem({id,title})}> Edit </button> </div> ); }; const TodoList = ({ items = [], index,editItem }) => { return items.map((p, index) => ( <TodoItem {...p} key={p.id} index={index} editItem={editItem} /> )); }; export default TodoList;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.