如何在 React JS 的 MultiSelect 组件的 props 中分配一个数组

How to assign an array at props of MultiSelect Component in React JS

我尝试在 React JS 的 MultiSelect 组件的 props "options" 分配一个数组,我需要数组中的特定格式,但屏幕是空白的,我得到 options.map 不是作为错误的函数,数组 return 成功(没关系),我不明白为什么会发生该错误。

我的代码是:

//I get data array

axios({
    method: 'get',
    url: `${URL}/suscripcion`,
    headers: {
        "Authorization": "bearer " + TOKEN
    }
}).then(respuesta => {
    let datos = respuesta.data;

    if (datos.success) {
        this.setState({
            Suscritos: datos.data
        });
        sus = this.state.Suscritos;
    } else {
        console.log("no")
    }
});


//Return array with format

Listarprueba() {
        if (this.state.Suscritos.length > 0) {
            return this.state.Suscritos.map((e, i) =>
            [
                {label: `${e.Email}`, value: `${e.Email}`}
            ]
            );
        }
    }

//Asign array at options

    options = this.Listarprueba();

//This is the MultiSelect Component

<div>
    <h1>Multiselect dropdown</h1>
    <Multiselect
        options={this.options}
        onSelectedChanged={this.handleSelectedChanged}
        selected={selected}
        isLoading={isLoading}
        disabled={isLoading}
        disableSearch={false}
        overrideStrings={{
            selectSomeItems: "do me a favor by selecting something",
            allItemsAreSelected: "You have gone nuts... all selected",
            selectAll: "do u wanna select all of them?",
            search: "Fantasy search"
        }}
    />
</div>

我得到数组的数据

这是错误

我在这里得到了例子https://codesandbox.io/s/3k3vjplo5

我认为错误是在选项属性中。

options={this.options}

想知道如何在react js中成功实现MultiSelect

好的,这是我的所有组件代码:

        import React, { Component, Fragment } from 'react';
        import { injectIntl } from 'react-intl';
        import { Colxx, Separator } from "Components/CustomBootstrap";
        import BreadcrumbContainer from "Components/BreadcrumbContainer";
        import IntlMessages from "Util/IntlMessages";
        import { Row, Card, CardBody, CardTitle, Input, Label, Button, } from "reactstrap";
        import ReactQuill from "react-quill";
        import "react-quill/dist/quill.snow.css";
        import 'react-quill/dist/quill.bubble.css';
        import { Formik, Field, Form } from 'formik';
        import * as Yup from 'yup';
        import axios from 'axios';
        import { URL, TOKEN } from 'Util/Config/Config';
        import SweetAlert from 'sweetalert-react';
        import Multiselect from "@khanacademy/react-multi-select";

        class CrearNotificacion extends Component {

            constructor(props) {
                super(props);
                this.state = {
                    textQuillBubble: "",
                    Suscritos: [],
                    sweetshow: false,
                    sweetTitle: '',
                    sweetText: '',
                    sweetType: '',
                    selected: [],
                    isLoading: true
                };
                this.handleChangeQuillBubble = this.handleChangeQuillBubble.bind(this);
            }

            Notificaciones = {
                Asunto: '',
                Suscripcion: '',
                Notificacion: '',
            }

    handleChangeQuillBubble(textQuillBubble) {
            this.setState({ textQuillBubble });
        }

        componentDidMount() {
            axios({
                method: 'get',
                url: `${URL}/suscripcion`,
                headers: {
                    "Authorization": "bearer " + TOKEN
                }
            }).then(respuesta => {
                let datos = respuesta.data;

                if (datos.success) {
                    this.setState({
                        Suscritos: datos.data
                    });
                    sus = this.state.Suscritos;
                } else {
                    console.log("no")
                }
            });
            setTimeout(() => {
                this.setState({
                    isLoading: false
                });
            }, 5000);
        }

    handleSelectedChanged = selected => {
            this.setState({ selected });
        };

        Guardar(value) {
            axios({
                method: 'post',
                url: `${URL}/notificacion`,
                headers: {
                    "Authorization": "bearer " + TOKEN,
                },
                data: {
                    Asunto: value.Asunto,
                    Suscripcion: value.Email,
                    Notificacion: this.state.textQuillBubble,
                }
            }).then((respuesta) => {
                let datos = respuesta.data;
                if (datos.success) {
                    this.setState({
                        sweetshow: true,
                        sweetText: datos.mensaje,
                        sweetTitle: "Mensaje",
                        sweetType: "success"
                    });
                } else {
                    this.setState({
                        sweetshow: true,
                        sweetText: datos.error,
                        sweetTitle: "Mensaje",
                        sweetType: "error"
                    });
                }
            });
        }

        Cancelar() {
            this.props.history.goBack();
        }

        Listarprueba() {
            if (this.state.Suscritos.length > 0) {
                return this.state.Suscritos.map((e, i) => (
                    { label: `${e.Email}`, value: `${e.Email}` }
                ));
            }
        }

        options = this.Listarprueba();

     render() {
            const { selected, isLoading } = this.state;
            return (
                <Fragment>
                    <Row>
                        <Colxx xxs="12">
                            <h1>{<IntlMessages id="menu.NewNoti" />}</h1>
                            <Separator className="mb-5" />
                        </Colxx>
                    </Row>
                    <Row className="mb-4">
                        <Colxx xxs="12">
                            <Card>
                                <CardBody>
                                    <Formik
                                        initialValues={this.Notificaciones}
                                        validationSchema={NotificacionSchema}
                                        onSubmit={value => {
                                            this.Guardar(value);
                                        }}
                                    >
                                        {({ errors, touched, values }) => (
                                            <div>
                                                <Form className="av-tooltip tooltip-label-bottom">
                                                    <Label className="form-group has-float-label">
                                                        <Field type="text" maxLength="45" name="Asunto" className="form-control" />
                                                        {errors.Asunto && touched.Asunto ? (
                                                            <div className="invalid-feedback d-block">{errors.Asunto}</div>
                                                        ) : null}
                                                        <IntlMessages id="forms.asunto" />
                                                    </Label>

<Label className="form-group has-float-label">
                                                    {/* <Field type="hidden" name="Mensaje"/> */}
                                                    <ReactQuill
                                                        theme="bubble"
                                                        value={this.state.textQuillBubble}
                                                        onChange={this.handleChangeQuillBubble}
                                                    />
                                                    {/* {errors.Mensaje && touched.Mensaje ? (
                                                        <div className="text-danger">{errors.Mensaje}</div>
                                                    ) : null} */}
                                                    <IntlMessages id="forms.Notificacion" />
                                                </Label>
                                                <div>
                                                    <h1>Multiselect dropdown</h1>
                                                    {console.log(this.state.Suscritos)}
                                                    <Multiselect
                                                        options={this.options}
                                                        onSelectedChanged={this.handleSelectedChanged}
                                                        selected={selected}
                                                        isLoading={isLoading}
                                                        disabled={isLoading}
                                                        disableSearch={false}
                                                        overrideStrings={{
                                                            selectSomeItems: "do me a favor by selecting something",
                                                            allItemsAreSelected: "You have gone nuts... all selected",
                                                            selectAll: "do u wanna select all of them?",
                                                            search: "Fantasy search"
                                                        }}
                                                    />
                                                    {/* {selected.join(", ")} */}
                                                </div>
                                                <br />
                                                <Button color="primary col-6" type="submit">
                                                    <IntlMessages id="forms.submit" />
                                                </Button>
                                                <Button color="secondary col-6" onClick={() => this.Cancelar()}>
                                                    <IntlMessages id="forms.Cancelar" />
                                                </Button>
                                            </Form>
                                        </div>
                                    )}
                                </Formik>
                                <SweetAlert
                                    show={this.state.sweetshow}
                                    title={this.state.sweetTitle}
                                    text={this.state.sweetText}
                                    type={this.state.sweetType}
                                    onConfirm={() => {
                                        this.setState({ sweetshow: false })
                                        this.props.history.push('app/Contacto/Notificaciones/Notificacion')
                                    }}
                                />
                            </CardBody>
                        </Card>
                    </Colxx>
                </Row>
            </Fragment>
        );
    }
}
export default injectIntl(CrearNotificacion);

将其更新为return对象数组,而不是数组数组,如下所示:

Listarprueba = () => {
  if (this.state.Suscritos.length > 0) {
    return this.state.Suscritos.map((e, i) => (
      {label: `${e.Email}`, value: `${e.Email}`}
    ));
  }
}

这个returns [{label:'emailstring', value:'emailstring'}, {},{}...];,你的原件是returning [ [{label:'emailstring', value:'emailstring'}],[{}], [{}], ...]

由于 rest 调用,您正在异步执行操作,因此它会在有数据之前尝试呈现。在渲染可能没有数据的东西之前做一个检查,比如

options={this.options ? this.options : []}

if (this.state && this.state.Suscritos && this.state.Suscritos.length > 0) {
...
}