Javascript ReactJS更新或删除arrayList中的项
这个问题可能会落空。我有一个Javascript ReactJS更新或删除arrayList中的项,javascript,reactjs,arraylist,Javascript,Reactjs,Arraylist,这个问题可能会落空。我有一个map()函数,数据来自API。当某些内容发生更改时,我需要在不刷新页面的情况下更改地图中的项目。我用的是findIndex。但有些原因是错误的。 现在我喜欢这个代码: const handleSubmit = values => { api.putItem(`users/${data.id}`, params) .then(res => { modelClose(); console.log(res);
map()
函数,数据来自API。当某些内容发生更改时,我需要在不刷新页面的情况下更改地图中的项目。我用的是findIndex。但有些原因是错误的。
现在我喜欢这个代码:
const handleSubmit = values => {
api.putItem(`users/${data.id}`, params)
.then(res => {
modelClose();
console.log(res);
let response = res.data;
let index = userForeignInfo.findIndex(response.id);
userForeignInfo.splice(index, 1, response);
setLoadingBtn(false);
}).catch(e => {
console.log(e.toString());
setLoadingBtn(false);
})
};
me中的userForeignInfo
函数如下所示:
const [userForeignInfo, setuserForeignInfo] = useState([]);
{userForeignInfo.map((item, index) =>
(
<li key={item.id} onClick={() => handlePassInfoShow(item)}>
{index + 1} {item.first_name} {item.last_name}
</li>
)
)}
现在通过api.put()方法保存数据。但是,重新加载页面后,阵列的状态将更新。我需要在不重新加载页面的情况下更改数组中的项。
我哪里错了?您修改了变量userForeignInfo
,但没有使用setuserForeignInfo
。因此,您的组件将不会更新
试着这样做:
const handleSubmit=data=>{//在此处用“data”重命名“value”
api.putItem(`users/${data.id}`,params)//params未在代码中定义。
。然后(res=>{
modelClose();
控制台日志(res);
让响应=res.data;
const newUserForeignInfo=[…userForeignInfo];//在使用splice之前在此处复制数组
让index=newUserForeignInfo.findIndex(response.id);
newUserForeignInfo.splice(索引,1,响应);
setuserForeignInfo(newUserForeignInfo);//更新此处的状态
设置加载BTN(错误);
}).catch(e=>{
log(例如toString());
设置加载BTN(错误);
})
};
谢谢,但没有任何更改。您建议的选项不起作用,也是同一个错误。我只是复制/粘贴了您的代码,但有一些错误。检查handleSubmit
参数<不使用代码>值
。也许你应该通过数据
来重命名它<代码>参数也未定义。您知道哪一行抛出TypeError吗?它应该在控制台输出中
TypeError: 7 is not a function