рендер выбрать в реакции - PullRequest
0 голосов
/ 27 апреля 2020

Нет ошибок. Множество динамических c из 18 элементов кажется правильным, тогда как myCompnent наблюдается в отладчике Chromium. Вопрос в том, как вы визуализируете Select в этом классе и сохраняете выбор для следующей переменной props.

Объект props, который является чистым Javascript Объектом, неправильно передается в класс ClusterSelection. Сервер Ajax обращается к серверу, который проходит по списку с заголовком и динамическим контентом c, разделенным двоеточиями. Массив с ключами создается и передается в модуль создания элемента Select.

class ClusterSelection extends React.Component {
  /*1*/
  constructor(props) {
    /*2*/
    super(props);
    this.state = {
      /*3*/
      theProps: this.props.value,
      error: null,
      isLoaded: false,
      items: ''
    };
    /* 3 */
  }
  /* 2 */
  componentDidMount() {
    /* 2 */
    fetch("http://www.localhost:8080/johntredden-1.0/userDesignatedSubCluster.html").then(res => res.json()).then(result => {
        /* 3 */
        this.setState({
          /* 4 */
          isLoaded: true,
          items: result
        });
        /* 4 */
        // alert("items:"+ result);
      },
      /* 3 */
      // Note: it's important to handle errors here
      // instead of a catch() block so that we don't swallow
      // exceptions from actual bugs in components.
      error => {
        /* 3 */
        this.setState({
          /* 4 */
          isLoaded: true,
          error
        });
        /* 4 */
      });
    /* 3 */
  }
  /* 2 */


  render() {
    /* 2 */
    const {
      error,
      isLoaded,
      items
    } = this.state;

    if (error) {
      return /*#__PURE__*/React.createElement("div", null, "Error: ", error.message);
    } else if (!isLoaded) {
      return /*#__PURE__*/React.createElement("div", null, "Loading cluster selection ...");
    } else {
      var response = parseJson.parseStart(this.state.items);
      var clusterTypes = response.split(':');
      var data = [];
      for(var i = 1; i < clusterTypes.length; i++){
        data.push({
          value: clusterTypes[i],
          label: clusterTypes[i]
        })
      }
      const myComponent = () => /*#__PURE__*/React.createElement(Select, {
        options: data
      });

      console.log("working U and V:" + this.state.theProps.getUdim() + " " + this.state.theProps.getVdim()); // print_recursive(this.state.theProps);       

      return "u dim: " + this.state.theProps.getUdim() + "v dim: " + this.state.theProps.getVdim() + " Bulk CLusters: " + myComponent;

    }
  }
  /* 2 */
}
/* 1 */

Ответы [ 2 ]

0 голосов
/ 03 мая 2020

У меня есть решение, но оно превращает динамический список c в список c. Он вводит зависимость на веб-странице на сервере. Я считаю это анти-паттерном. Я до сих пор не нашел пример динамического c компонента выбора.

                class ClusterSelection extends React.Component {
                  /*1*/
                  constructor(props) {
                    /*2*/
                    super(props);
                    this.state = {
                      /*3*/
                      theProps: this.props.value,
                      error: null,
                      isLoaded: false,
                      items: "",
                      value: "",
                    };
                    /* 3 */

                    this.handleChange = this.handleChange.bind(this);
                    this.handleSubmit = this.handleSubmit.bind(this);
                  }
                  /* 2 */

                  handleChange(event) {
                    this.setState({
                      value: event.target.value,
                    });
                  }

                  handleSubmit(event) {
                    alert("first choice is: " + this.state.value);
                    event.preventDefault();
                    this.setState({
                      /* 3 */ submitted: true,
                    }); /* 3 */
                  }

                  componentDidMount() {
                    /* 2 */
                    fetch(
                      "http://www.localhost:8080/johntredden-1.0/userDesignatedSubCluster.html"
                    )
                      .then((res) => res.json())
                      .then(
                        (result) => {
                          /* 3 */
                          this.setState({
                            /* 4 */
                            isLoaded: true,
                            items: result,
                          });
                          /* 4 */
                          // alert("items:"+ result);
                        },
                        /* 3 */
                        // Note: it's important to handle errors here
                        // instead of a catch() block so that we don't swallow
                        // exceptions from actual bugs in components.
                        (error) => {
                          /* 3 */
                          this.setState({
                            /* 4 */
                            isLoaded: true,
                            error,
                          });
                          /* 4 */
                        }
                      );
                    /* 3 */
                  }
                  /* 2 */

                  render() {
                    /* 2 */
                    const { error, isLoaded, items } = this.state;

                    if (error) {
                      return /*#__PURE__*/ React.createElement(
                        "div",
                        null,
                        "Error: ",
                        error.message
                      );
                    } else if (!isLoaded) {
                      return /*#__PURE__*/ React.createElement(
                        "div",
                        null,
                        "Loading cluster selection ..."
                      );
                    } else {
                      var response = parseJson.parseStart(this.state.items);
                      var clusterTypes = response.split(":");
                      var data = [];

                      for (var i = 1; i < clusterTypes.length; i++) {
                        data[i] = clusterTypes[i];
                      }

                      //                          const myComponent = () => /*#__PURE__*/React.createElement("select", {
                      //                            options: data,
                      //                            onChange: this.handleChange
                      //                          });

                      console.log(
                        "working U and V:" +
                          this.state.theProps.getUdim() +
                          " " +
                          this.state.theProps.getVdim()
                      ); // print_recursive(this.state.theProps);

                      return this.state.submitted
                        ? /*#__PURE__*/ React.createElement(ClusterSelectionResponse, {
                            /* 3 */ value: this.state.theProps,
                            value2: this.state.value,
                          })
                        : /*#__PURE__*/ React.createElement(
                            "form",
                            {
                              onSubmit: this.handleSubmit,
                            },
                            /*#__PURE__*/ React.createElement(
                              "label",
                              null,
                              "Select cluster configuration:",
                              /*#__PURE__*/ React.createElement(
                                "select",
                                {
                                  value: this.state.value,
                                  onChange: this.handleChange,
                                },
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                   value: " ",
                                  },
                                  "Select cluster type"
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[1],
                                  },
                                  data[1]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[2],
                                  },
                                  data[2]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[3],
                                  },
                                  data[3]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[4],
                                  },
                                  data[4]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[5],
                                  },
                                  data[5]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[6],
                                  },
                                  data[6]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[7],
                                  },
                                  data[7]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[8],
                                  },
                                  data[8]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[9],
                                  },
                                  data[9]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[10],
                                  },
                                  data[10]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[11],
                                  },
                                  data[11]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[12],
                                  },
                                  data[12]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[13],
                                  },
                                  data[13]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[14],
                                  },
                                  data[14]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[15],
                                  },
                                  data[15]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[16],
                                  },
                                  data[16]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[17],
                                  },
                                  data[17]
                                ),
                                /*#__PURE__*/ React.createElement(
                                  "option",
                                  {
                                    value: data[18],
                                  },
                                  data[18]
                                )
                              )
                            ),
                            /*#__PURE__*/ React.createElement("input", {
                              type: "submit",
                              value: "Submit",
                            })
                          );
                    }
                  }
                  /* 2 */
                }
                /* 1 */
0 голосов
/ 28 апреля 2020

Я считаю, что этот код ближе. Одна из проблем, с которыми я столкнулся, состоит в том, что все «избранные» примеры используют жестко закодированный список. Как обработать динамический список c?

Ниже приведены подробные сведения об ошибке:

json1: Подкластеры: DOUBLESTAR_BINARY_1: DOUBLESTAR_BINARY_0: THREESTAR_TRINARY_0: THREESTAR_TRINARY__TAR_TAR FOURSTAR_TRINARYPLUSONE_TRINARY_0: FOURSTAR_TRINARYPLUSONE_TRINARY_1: FOURSTAR_2BINARIES_1_BINARY_0: FOURSTAR_2BINARIES_0_BINARY_0: FOURSTAR_2BINARIES_1_BINARY_1: FOURSTAR_2BINARIES_0_BINARY_1: нЕТ: THREESTAR_BINARYPLUSONE_BINARY_0: THREESTAR_BINARYPLUSONE_BINARY_1: THREESTAR_BINARYPLUSONE_2 indexReactBuild8 html:. 377 работает U и V:. 2 2 среагировать-dom.development js: 14894 Uncaught Ошибка: объекты не являются допустимо как дочерний элемент React (найдено: объект с ключами {myComponent}). Если вы хотите отобразить коллекцию дочерних элементов, используйте вместо этого массив. в метке (созданной ClusterSelection) в форме (созданной ClusterSelection) в ClusterSelection (созданной AjaxProcess) в AjaxProcess (созданной NameProcess) в NameProcess (созданной NameForm) в NameForm в throwOnInvalidObjectType (react-dom.development. js: 14894) в createChild (Reaction-dom.development. js: 15127) в reconcileChildrenArray (реагировать-dom.development. js: 15378) в reconcileChildFibers (реагировать-dom.development. js: 15744) в согласоватьChildren ( response-dom.development. js: 18235) в updateHostComponent (react-dom.development. js: 18757) в beginWork $ 1 (react-dom.development. js: 20339) в HTMLUnknownElement.callCallback (реаги- dom.development. js: 330) в Object.invokeGuardedCallbackDev (Reaction-dom.development. js: 379) в invokeGuardedCallback (реаги-dom.development. js: 434)

Обновленный код

                class ClusterSelection extends React.Component {
                  /*1*/
                  constructor(props) {
                    /*2*/
                    super(props);
                    this.state = {
                      /*3*/
                      theProps: this.props.value,
                      error: null,
                      isLoaded: false,
                      items: '',
                      value: ''
                    };
                    /* 3 */

                    this.handleChange = this.handleChange.bind(this);
                    this.handleSubmit = this.handleSubmit.bind(this);
                  }
                  /* 2 */


                  handleChange(event) {
                    this.setState({
                      value: event.target.value
                    });
                  }

                  handleSubmit(event) {
                    alert('first choice is: ' + this.state.value);
                    event.preventDefault();
                  }

                  componentDidMount() {
                    /* 2 */
                    fetch("http://www.localhost:8080/johntredden-1.0/userDesignatedSubCluster.html").then(res => res.json()).then(result => {
                      /* 3 */
                      this.setState({
                        /* 4 */
                        isLoaded: true,
                        items: result
                      });
                      /* 4 */
                      // alert("items:"+ result);
                    },
                    /* 3 */
                    // Note: it's important to handle errors here
                    // instead of a catch() block so that we don't swallow
                    // exceptions from actual bugs in components.
                    error => {
                      /* 3 */
                      this.setState({
                        /* 4 */
                        isLoaded: true,
                        error
                      });
                      /* 4 */
                    });
                    /* 3 */
                  }
                  /* 2 */


                  render() {
                    /* 2 */
                    const {
                      error,
                      isLoaded,
                      items
                    } = this.state;

                    if (error) {
                      return /*#__PURE__*/React.createElement("div", null, "Error: ", error.message);
                    } else if (!isLoaded) {
                      return /*#__PURE__*/React.createElement("div", null, "Loading cluster selection ...");
                    } else {
                      var response = parseJson.parseStart(this.state.items);
                      var clusterTypes = response.split(':');
                      var data = [];

                      for (var i = 1; i < clusterTypes.length; i++) {
                        data[i] = clusterTypes[i];
                      }

                      const myComponent = () => /*#__PURE__*/React.createElement("select", {
                        options: data,
                        onChange: this.handleChange
                      });

                      console.log("working U and V:" + this.state.theProps.getUdim() + " " + this.state.theProps.getVdim()); // print_recursive(this.state.theProps);       

                      return /*#__PURE__*/React.createElement("form", {
                        onSubmit: this.handleSubmit
                      }, /*#__PURE__*/React.createElement("label", null, "select cluster type:", {
                        myComponent
                      }, /*#__PURE__*/React.createElement("input", {
                        type: "submit",
                        value: "Submit"
                      })));
                    }
                  }
                  /* 2 */
                }
                /* 1 */
...