简体   繁体   English

Select 并使用 react 和 hooks 取消选择值

[英]Select and deselect values with react and hooks

I am trying to change the state by selecting and deselecting the language option in the code below.我正在尝试通过在下面的代码中选择和取消选择语言选项来更改 state。 So far I can update the state by adding a language, my problem is that, if I click on the same language again, I will add it another time to the array.到目前为止,我可以通过添加语言来更新 state,我的问题是,如果我再次单击相同的语言,我会再次将其添加到数组中。 Can anyone explain me how to add or remove the language from the array when clicked one more time?谁能解释我再次单击时如何在数组中添加或删除语言?

export default function Dashboard(props) {

const [language, setLanguage] = useState('');

const handleLanguageChange = changeEvent => {
    changeEvent.persist()
    setLanguage(prevState => [...prevState, changeEvent.target.value])
  };

}

You will need a good old check.你需要一张好的旧支票。

if (!languages.includes(changeEvent.target.value) {
    // code to add the language
}

It looks like your only issue is your logic in the place where you are handling update.看起来您唯一的问题是您在处理更新的地方的逻辑。 Usage of hooks is correct So first of all you need to set proper initial value.钩子的使用是正确的所以首先你需要设置适当的初始值。 As you plan to store your languages in an array.当您计划将语言存储在数组中时。

Second part is updating the array.第二部分是更新数组。 So you can either find clicked language in the array and if it is exist - then use filter to set your new value or filter and compare length of existing array and new one.因此,您可以在数组中找到单击的语言以及是否存在 - 然后使用filter设置新值或过滤并比较现有数组和新数组的长度。

const [language, setLanguage] = useState([]);

const handleLanguageChange = changeEvent => {
    changeEvent.persist()
    setLanguage(prevState => {
            const lang = changeEvent.target.value;

            if (prevState.includes(lang) {
                return prevState.filter(el => el !== lang);
            }

            return [...prevState, lang]
        })
  };

Check the selected value using find() method on language array if it returns undefined, then push into array.如果返回未定义,则使用语言数组上的find()方法检查所选值,然后推入数组。 Rename the state variable as languages otherwise it's confusing (Naming convention standard).将 state 变量重命名为languages ,否则会造成混淆(命名约定标准)。

const [languages, setLanguages] = useState('');

const handleLanguageChange = changeEvent => {
    changeEvent.persist()
    if (!languages.find(value => value == changeEvent.target.value)) {
        setLanguages(prevState => [...prevState, changeEvent.target.value])
    }
};

2 Things here 2 这里的东西

  1. Instead of having而不是拥有

     <option value="Deutsch">Deutsch</option> <option value="Englisch">Englisch</option>

use an languages array of json so it bacomes easy for you to add them like使用 json 的语言数组,因此您可以轻松添加它们

 languages= [{value='Deutsch',name= 'Deutsch',...}] 

2.setLanguage sa a direct value 2.setLanguage sa直接取值

setLanguage(changeEvent.target.value)

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

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