简体   繁体   English

在 Reactjs 中使用 prevState 时如何将数组设置为空数组

[英]How to set an array to empty array when using prevState in Reactjs

I am using prev state to append the array and I need to set the whole array to an empty array on the button clicked.我正在使用 prev state 到 append 数组,我需要在单击的按钮上将整个数组设置为空数组。 I tried using setArray({}) but it doesn't work.我尝试使用 setArray({}) 但它不起作用。 how to completely set the array to an empty array on button click如何在按钮单击时将数组完全设置为空数组

import React, {useState,useEffect} from 'react'

function testFunction() {

    const [features, setFeatures] = useState({});

    const add = (key,value) => {
        setFeatures((prevFeatures)=>({...prevFeatures,[key]: value}));
    }

    const clear =() =>{
        setFeatures({});
    }

    return (
        <div>
            
            <div>
                <select onChange={(event)=>add(event.target.name,event.target.value)}>
                    <option name="opt1" value="val1">Value1</option>
                    <option name="opt2" value="val2">Value2</option>
                    <option name="opt3" value="val3">Value3</option>
                    <option name="opt4" value="val4">Value4</option>
                    <option name="opt5" value="val5">Value5</option>
                </select>
            </div>

            <button type="reset" value="reset" onClick={()=>clear}>Reset</button>

        </div>
    )
}
export default testFunction

First of all you didn't initialize your state as an array?首先,您没有将 state 初始化为数组? So first let's do that;所以首先让我们这样做;

const [features, setFeatures] = useState([])

also your functions should be like this;你的功能也应该是这样的;

 const add = (key,value) => {
        setFeatures((prevFeatures)=>([...prevFeatures, {[key]: value} ])); // key, value added to array of Objects
    }

    const clear =() =>{
        setFeatures([]); // setting empty array
    } 

also you should call clear function;你也应该打电话清除 function;

<button type="reset" value="reset" onClick={()=>clear()}>Reset</button>

You must execute your function clear because in your code you are only passing the declared function.你必须执行你的 function clear因为在你的代码中你只传递了声明的 function。

<button type="reset" value="reset" onClick={()=>clear}>Reset</button>

onClick={()=>clear} must be replaced for onClick={()=>clear()} or onClick={clear} onClick={()=>clear}必须替换为onClick={()=>clear()}onClick={clear}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM