简体   繁体   English

从props React JS返回对象数组

[英]return array of objects from props React JS

so I have the following component that is a dropdown list created using react-select . 所以我有以下组件,它是使用react-select创建的下拉列表。

import React from 'react'
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
];


class MealsFilters extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedOption: null,
    };
  }

  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  }

  render() {
    const { selectedOption } = this.state;
    return (
      <div className="container my-3">
        <div className="row">
          <div className="col-lg-4 col-md-6 col-sm-8">
            <Select
            isMulti
            isSearchable
            placeholder={"catégories"}
            value={selectedOption}
            onChange={this.handleChange}
            options={options}
            />
          </div>
        </div>
      </div>
    )
  }
}

export default MealsFilters;

the options variable is the default one from the docs. options变量是文档中的默认变量。 I actually need to replace its values by each meal category available. 我实际上需要用每个可用的餐食类别替换其值。 To do so, as you can see, I need to create an array of objects with a value and a label . 如您所见,要做到这一点,我需要创建一个带有valuelabel的对象数组。

this component accesses meal categories through props called meals that are like so: 该组件通过称为“ meals道具访问进餐类别,如下所示:

console.log(this.props.meals);

=> [{
     id: 0,
     name: spaghettis,
     category: italian,
     price: 5.99},
    {
     id: 1,
     name: hamburger,
     category: american,
     price: 7.99},
     {
      etc.
      }, {}]

How can I take advantage of this.props.meals to get my options array of objects ? 我如何利用this.props.meals获取我的options对象数组?

EDIT: multiple meals can have the same category, and I need each category to only appear once in the options. 编辑:多餐可以具有相同的类别,我需要每个类别在选项中仅出现一次。

You could do something like this: 您可以执行以下操作:

options={this.props.meals.map(
  ({id, name})=>({value:id,label:name})
)}

You could also use redux connect to create a container that will map the data to dropdown values for you 您还可以使用redux connect创建一个容器,该容器将为您映射数据到下拉值

You can merge the data by category in the following way: 您可以通过以下方式按类别合并数据:

 var items = [ { id: 0, name: 'spaghettis', category: 'italian', price: 5.99, }, { id: 1, name: 'hamburger', category: 'american', price: 7.99, }, { id: 2, name: 'other hamburger', category: 'american', price: 7.99, }, ]; console.log( [ ...items.reduce( (result, item) => ( result.get(item.category) ? result.get(item.category).push(item.id) : result.set(item.category, [item.id]), result ), new Map(), ), ].map(([label, value]) => ({ label, value })), ); 

In the component it'll look like this: 在组件中,它将如下所示:

options={[
  ...this.props.meals.reduce(
    (result, item) => (
      result.get(item.category)
        ? result.get(item.category).push(item.id)
        : result.set(item.category, [item.id]),
      result
    ),
    new Map(),
  ),
].map(([label, value]) => ({ label, value }))}

Map over your this.props.meals array, and create the needed options array, 映射到您的this.props.meals数组,并创建所需的options数组,

<Select
    isMulti
    isSearchable
    placeholder={"catégories"}
    value={selectedOption}
    onChange={this.handleChange}
    options={this.props.meal.map(item=>({value: item.id, label: item.name}))}
/>

You only need the "name" property so when you map through meals, simply retrieve it. 您只需要“名称”属性,因此在绘制餐点地图时,只需对其进行检索。 Then upper case the first letter. 然后大写第一个字母。

 const meals = [{ id: 0, name: "spaghettis", category: "italian", price: 5.99 }, { id: 1, name: "hamburger", category: "american", price: 7.99 } ] const result = meals.map(({name}) => ({ label: `${name[0].toUpperCase()}${name.slice(1)}`, value: name })) console.log(result); 

You can use getOptionLabel and getOptionValue props. 您可以使用getOptionLabelgetOptionValue道具。

<Select
    options={this.props.meals},
    getOptionLabel={m => m.name}
    getOptionValue={m => m.id} />

https://react-select.com/props https://react-select.com/props

getOptionLabel generic = (option) => string

Resolves option data to a string to be displayed as the label by components 将选项数据解析为字符串,以按组件显示为标签

getOptionValue generic = (option) => string

Resolves option data to a string to compare options and specify value attributes 将选项数据解析为字符串以比较选项并指定值属性

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

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