繁体   English   中英

反应映射复选框重复返回所有数组元素,而不只是我检查过的那些

[英]React mapped checkbox repeating back all of the array elements, instead of just the ones i've checked

视觉:我在左边使用的表格,右边是输出

我试图在React中使用复选框数组映射来显示某件事的功能,但是当我打印出元素时,在提交表单和数据库后,每个数组元素都会显示在前端网页的表中而不只是我检查过的那些。 所有这些都被报告回MongoDB数据库,并且一切正常(我通过将发送到那里的内容更改为简单的String输入并显示正常来进行检查),所以我很肯定映射是问题。 谢谢!

构造函数:

constructor(props) {
    super(props);
    this.state = {
        name: '',
        price: '',
        location: ['Back Bay', 'Downtown Crossing'],
        description: '',
        features: [
            'Pet-Free', 'Climate-Controlled', 'Locked Area', 'Private Entrance', 'Smoke Detectors', 'Smoke Free'
        ],
    };

        this.onInputChange = this.onInputChange.bind(this);

    this.addListingService = new ListingService();
    this.handleSubmit = this.handleSubmit.bind(this);
}

这是我的映射:

<div>What cool features does this storage space have?</div>
  {
   this.state.features.map((features) => {
              return <CheckBox key={features} title={features} name="features" />
             })
               }

编辑:

我还尝试使用onInputChange()函数来查看是否会触发它,因此只有我选中的复选框选项才会出现在前端页面和数据库中,但这似乎无济于事。 我已附上一张照片,显示我正在使用的表格和输出。 这是该函数:

        onInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value,
        });
    }

编辑2:

我现在按照下面的建议尝试键映射,但是ObjectKeys函数出现错误。 我收到的错误提示“ TypeError:Object.assign(...)。filter不是一个函数”

   Object.keys(this.state.features).map(key =>({...this.state.features[key],title:key}
                                    .filter(features=>features.checked)
                                    .map(features => <CheckBox key={features} title={features} onChange = {this.onInputChange} />)))

如果只想显示数组的某些元素,则可以使用Array.prototype.filter

this.state.features
    .filter(features=>features.checked)
    .map(feature => <CheckBox key={feature.id} title={feature.title} name="features" />)

这只会显示您已选中项目的复选框。 当返回true进行过滤时,它将保留该项目,而false则不保留。 注意:这不会修改您的原始数组。 我的方法需要您稍微重构数据。 您可能需要一系列看起来像这样的功能

[
    {id:1,title:'Pet-Free',checked:true},
    {id:2,title:'Climate-Controlled',checked:false},
    // ...etc
]

暂无
暂无

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

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