我有一个‘List’组件,它允许您将项添加到状态数组中,然后从状态显示它.然后,用户可以(或者应该能够)删除这些列表项.

该组件中有四个状态props :

  • CurrentList:输入中要添加到列表数组中的内容
  • SetCurrentList:用于更改输入内容的内容
  • FullList:完整的数组列表
  • SetFullList:用于将CurrentList内容添加到数组中,并移除

我使用.Filter()创建状态数组的副本,然后在此函数中设置状态:

const deleteFromList = (e) => {

        console.log("Delete button pressed")
        console.log(e)

        let fullList = props.fullListState
        let setFullList = props.setFullListState

        let filteredArray = fullList.filter(item => item)

        setFullList(filteredArray)
    }

然而,每次我执行这个函数时(即按下Delete按钮时),它只会创建一个循环,并且前两个console.Logs只是重复执行.

这是完整的返回函数本身:

<>
            <label className="setup-jobs-label">{props.label}</label>
            <div className="setup-jobs-input-container">
                <input className="setup-jobs-alt-input" type="text" onChange={onChange} value={props.currentListState} />
                <button className="setup-jobs-add-button" onClick={addToList}>Add</button>
            </div>
            { props.fullListState === [] ? null : props.fullListState.map(x => {
                return <div className="setup-jobs-input-container" key={props.fullListState[x]}>
                    <p className="setup-jobs-input-paragraph">{x}</p>
                    <button className="setup-jobs-delete-button" onClick={deleteFromList(x)}>Delete</button>
                </div>
            }) }
        </>

最重要的一点是底层的条件呈现,它判断状态数组是否为空,如果为空,则不显示任何内容.如果不是,则返回NULL.

任何建议都将不胜感激--不确定我在过滤器函数中做错了什么.

推荐答案

onClick处理程序中,您传递deleteFromList的执行结果,您应该改为传递对此函数的引用:

// note the '() =>' 
<button className="setup-jobs-delete-button" onClick={() => deleteFromList(x)}>Delete</button>

有关这方面的更多详细信息,请参见https://reactjs.org/docs/handling-events.html.

除此之外,您的筛选器逻辑似乎不正确:

// this line only removes falsy values, but not the "e" values
let filteredArray = fullList.filter(item => item)

// you should implement something like this
let filteredArray = fullList.filter(item => [item is not "e"])
// this should work as we work on objects references
let filteredArray = fullList.filter(item => item !== e)

Reactjs相关问答推荐

更新数据时有关CQR和更新UI的问题

阻止在ShadCN和React中的FormLabel中添加 colored颜色

TypeError:b不是React.js中的函数错误

单击空白区域时,Reaction Multiple下拉组件不关闭

UseEffect和useSelector的奇怪问题导致无限循环

为什么我的react虚拟化列表不显示滚动条,除非我确保高度低于rowCount*rowHeight?

一键MUI导出

左边框不在图表中显示

Next.js Next-Auth登录函数重定向到http://localhost:3000/api/auth/error

Antd V5组件自定义主题

Mui 在 TextField 标签上添加工具提示显示两个工具提示框

当`useSelector`回调中的属性值更新时,将会使用更新后的值吗?

在遵循 react-navigation 的官方文档时收到警告消息

如何使用 redux 和 react-plotly.js

ReactJS:在导航栏中使用 Select inside Link 组件时如何避免重定向?

React:如何设置光标 Select

Material UI:使用 mui 手风琴时出现props 类型失败:isValidElement 不是函数

在 Remix 中使用 chartjs 和 react-chartjs-2 会出现错误react-chartjs-2未在您的 node_modules 中找到

哪个是创建 React 应用程序的更好方法?

React useEffect hooks return () => cleanup() vs return cleanup