Handling .map and if/else statement for react rend

2019-07-31 19:31发布

I am using react-select and the creatable function that allows you to create a new select option - just type in the select/input field on example. When you type in the first custom option it defaults into a group called "new Group". When you create a 2nd custom option this should overwrite the first in the new group. However the group name disappears.

This is the incorrect code that results in that behavior...

  if (this.state.hasCreatedOption) {
    options[this.state.hasCreatedOption] = newOption;
  } else {
    options.map(option => {
      if (option.label === "New group") {
        return {
          label: option.label,
          options: option.options.push(newOption)
        };
      }
      return option;
    });
  }

  hasCreatedOption = options.length - 1;

Here is the example created - https://codesandbox.io/s/w761j8v855

2条回答
▲ chillily
2楼-- · 2019-07-31 20:05

I came up with this answer:

  if (this.state.hasCreatedOption) {
    options[this.state.hasCreatedOption].options[0] = newOption;
  } else {
    options.map(option => {
      if (option.label === "New group") {
        return {
          label: option.label,
          options: option.options.push(newOption)
        };
      }
      return option;
    });
  }

  hasCreatedOption = options.length - 1;

The false outcome was overwriting the top level property and recreating it without its label. Not sure if there is a better way here.

查看更多
Luminary・发光体
3楼-- · 2019-07-31 20:09

As in your case you know that your custom option group is at the very end of your options array, I would even right less code and improve the speed / performance of it with the following code:

state = {
    value: this.props.options[0].options,
    options: this.props.options,
    hasCreatedOption: this.props.options.length - 1
  };
  handleCreate = input => (inputValue: any) => {
    this.setState({ isLoading: true });

    setTimeout(() => {
      const { options } = this.state;
      const newOption = createOption(inputValue);
      options[this.state.hasCreatedOption].options[0] = newOption;

      this.setState({
        isLoading: false,
        options: [...options],
        value: newOption,
        formatGroupLabel: "new label"
      });
      input.onChange(newOption);
    }, 1000);
  };

As you declare your custom option group you basically know the index of it and can directly update the right array without looping through all of the different group you may have. Here the example.

查看更多
登录 后发表回答