首页 > 解决方案 > 在 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 []

唯一的问题是屏幕上显示的数组不会更新,换句话说,屏幕上显示的数组在单击按钮后不会改变,它仍然显示包含所有项目的整个数组。

如何映射数组的更改版本,或者我在映射不显示更改版本的数组时做错了什么?

标签: javascriptarraysreactjs

解决方案


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.


推荐阅读