React 映射复选框重复所有数组元素,而不仅仅是我检查过的元素



visual:我在左侧使用的形式,右输出

我正在尝试在react中使用复选框数组映射以显示某些内容的功能,但是当我在提交表单和表单和表单和在我的数据库中,而不仅仅是我检查的数据库。所有这些都被报告回MongoDB数据库,这很好(我通过将其发送到简单的字符串输入并显示出来的内容进行检查了),所以我很肯定地映射是问题。谢谢!

构造函数:

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(...)。过滤器不是函数"

   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
]

相关内容

最新更新