javascript - 在 react js 中对数组进行更改后如何映射数组?
问题描述
我正在映射一个数组,每个数组都有一个按钮可以从数组中删除它:
const comments = [ 'Hey', 'Yo' ];
{comments.map((each, index) => {
return (
<div key={index}>
<button
onClick={() => {
console.log(comments.indexOf(each));
const id = comments.indexOf(each);
comments.splice(id, 1);
console.log(comments);
}}
>
Button
</button>
</div>);
}
单击该按钮时,该项目将被删除,并且它在删除它后控制台记录该数组并且它工作正常。
1
App.js:17 ["Hey"]
App.js:14 0
App.js:17 []
唯一的问题是屏幕上显示的数组不会更新,换句话说,屏幕上显示的数组在单击按钮后不会改变,它仍然显示包含所有项目的整个数组。
如何映射数组的更改版本,或者我在映射不显示更改版本的数组时做错了什么?
解决方案
You must have to use useState.
import React, { useState } from 'react';
const [comments, setComments ] = useState([ 'Hey', 'Yo' ]);
and inside your onClick function:
setComments(comments.filter((comment, index)=>index!==id));
I used .filter because your use of splice will return the cutted element of the array.
推荐阅读
- android - 用户撤销权限
- rx-java - 订阅 ConnectableObservable 的观察者在 connect 方法后没有得到通知
- javascript - 2 函数异步结果 2.get,post 函数
- php - phalcon phql 在 where 中查找带有数组元素的查询
- postgresql - 公共架构上新用户的默认权限?
- sql - 如何在Oracle SQL中将excel序列日期号转换为日期
- rethinkdb-python - Rethinkdb:在整个表中搜索一个字符串(全文搜索)
- cuda - NV 工具包扩展包括文件位置 - Linux 与 Windows
- kubernetes - K8s ingress:nginx入口控制器未处于运行模式
- python - 如何根据内容裁剪图像(Python 和 OpenCV)?