Javascript 为什么setItem不是';t出租';编辑按钮';工作
我试图在简单挂钩的帮助下,为每个项目设置一个编辑按钮。我已使用映射查看项目的元素。。。。但不知怎的,它不起作用了……当按下按钮时,什么也没有显示。。。。。 代码沙盒链接: app.js:Javascript 为什么setItem不是';t出租';编辑按钮';工作,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我试图在简单挂钩的帮助下,为每个项目设置一个编辑按钮。我已使用映射查看项目的元素。。。。但不知怎的,它不起作用了……当按下按钮时,什么也没有显示。。。。。 代码沙盒链接: app.js: import React,{useState}来自“React”; 从“/TodoFiles/TodoList”导入TodoList; const defaultItems=[ {id:1,标题:“编写反应Todo项目”,完成:true}, {id:2,标题:“上传到github”,完成:false} ]; 常
import React,{useState}来自“React”;
从“/TodoFiles/TodoList”导入TodoList;
const defaultItems=[
{id:1,标题:“编写反应Todo项目”,完成:true},
{id:2,标题:“上传到github”,完成:false}
];
常量应用=()=>{
const[items,setItems]=useState(defaultItems)
const editItem=({id,title})=>{
setItems(items.map(p=>p.id==id?{…p,title}:p))
}
返回(
);
};
导出默认应用程序;
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;
从“React”导入React;
const TodoItem=({title,completed,editItem})=>{
返回(
{title}
编辑项(标题)}>
编辑
);
};
常量TodoList=({items=[],index,editItem})=>{
返回项目。映射((p,索引)=>(
));
};
将默认值导出到列表;
我不想在自定义挂钩中使用useEffect或useReducer。。。因为我想练习基础知识。对不起,我经常问你问题,我正在努力学习,我不想放弃。。。如果可能的话,请您事先用纯文本解释一下它为什么不起作用。您忘了将
id
传递给editItem
功能,请点击TodoItem
组件
另外,您不应该在setState函数中像那样使用旧状态(在editItem
函数中)。您应该使用updater函数参数。正因为如此,您始终可以修改当前状态
const editItem = ({id,title}) => {
setItems(oldItems => (olditems.map(p=>p.id===id?{...p,title}:p)))
}
从“React”导入React;
const TodoItem=({id,title,completed,editItem})=>{
返回(
{title}
编辑项({id,title})}>
编辑
);
};
常量TodoList=({items=[],index,editItem})=>{
返回项目。映射((p,索引)=>(
));
};
将默认值导出到列表代码>您只将标题传递给TodoItem中的editItem。id如何?已更改它…但“编辑”按钮仍不起作用。。。。const TodoItem=({id,title,completed,editItem})=>{return({title}editItem({id,title})}>Edit);};constToDoList=({items=[],editItem})=>{returnitems.map((p)=>());};这有什么意义吗?我的意思是您只更改了变量名。但一切都是一样的。你认为它会如何工作??这仍然是变化…不起作用。。。最终更改变量没有效果我没有只更改变量名,我添加了更新程序函数:setItems(oldItems=>(oldItems.map(p=>p.id==id?{…p,title}:p)))我根据你的建议进行了编辑。下面是代码和链接:我不知道该怎么做?我应该声明另一个函数或切换吗?
const editItem = ({id,title}) => {
setItems(oldItems => (olditems.map(p=>p.id===id?{...p,title}:p)))
}