猿问

ReactJS:如何防止 array.push 中的重复值?

此时在选择框中选择一个选项时,其余选项将变为多个值。我怎样才能防止这种重复值?


import Select from 'react-select';

const dataOptions = []; 

class App extends React.Component {

    constructor(props) {

        super(props);

        this.data = [];

        this.getData();

    }

    getData = () => { api.request({url: `/getdata`}).then(res => res.map(el => this.data[el.id] = el.name)) }


    addData = () => {

        const { selectedId } = this.state;

        var datas = this.data;

        console.log(datas);

        datas.map((name, index) => {

            if (!dataOptions.includes(name)) {

                console.log('b4 push:', dataOptions)

                dataOptions.push({ value: index, label: name });

                console.log('aftr push:', dataOptions)

            }

        });

        return (

            <Select options={dataOptions}

            isMulti

            />

        );

    }

}

此语法中发生了一些错误:


datas.map((name, index) => {

  if (!dataOptions.includes(name)) {

       dataOptions.push({ value: index, label: name });

  }

}); 

控制台结果


[ "data-1", "data-2", "data-3"]


b4 push: [

  {value: 1, label: "data-1"}

  {value: 2, label: "data-2"}

  {value: 3, label: "data-3"}

]


aftr push: [

  {value: 1, label: "data-1"}

  {value: 2, label: "data-2"}

  {value: 3, label: "data-3"}

]

PS:在后推我已经从下拉菜单中选择了第一个选项;所以结果 if 不应该显示在数组值中。


提前致谢...!


芜湖不芜
浏览 306回答 1
1回答

白猪掌柜的

该destructuring语法应该像下面datas.map(({name, index}) => {&nbsp; &nbsp; &nbsp; if (!dataOptions.includes(name)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dataOptions.push({ value: index, label: name });&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp;此外,您不需要外部数组来将数据推送到 map 函数中,因为该函数默认返回一个数组,您可以像下面这样简单地做&nbsp;let expected_data=datas.map(({name, index}) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!dataOptions.includes(name)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return&nbsp; { value: index, label: name };// return a value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;该expected_data项目将包含手术后需要的数据看片段——let data = [{&nbsp; "name": 1,&nbsp; "index": 2}, {&nbsp; "name": 11,&nbsp; "index": 21}]console.log(data.map(({&nbsp; index,&nbsp; name}) => {&nbsp; return {&nbsp; &nbsp; value: index,&nbsp; &nbsp; label: name&nbsp; }}))你最好使用Array.some()你正在寻找的东西&nbsp;datas.map((name,index) => { // here index is the iterator&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!dataOptions.some(({value,label})=>label==name&nbsp; ))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;dataOptions.push({ value: index, label: name });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答