【问题标题】:Handling .map and if/else statement for react render - using React-select处理反应渲染的 .map 和 if/else 语句 - 使用 React-select
【发布时间】:2018-11-12 11:38:28
【问题描述】:

我正在使用 react-select 和可创建的功能,它允许您创建新的选择选项 - 只需在示例中输入选择/输入字段。当您输入第一个自定义选项时,它默认进入一个名为“新组”的组。当您创建第二个自定义选项时,这应该会覆盖新组中的第一个。但是组名消失了。

这是导致该行为的错误代码...

  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;

这是创建的示例 - https://codesandbox.io/s/w761j8v855

【问题讨论】:

    标签: javascript reactjs react-redux react-select


    【解决方案1】:

    在您的情况下,您知道您的自定义选项组位于选项数组的最后,我什至会减少代码并使用以下代码提高它的速度/性能:

    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);
      };
    

    当您声明自定义选项组时,您基本上知道它的索引,并且可以直接更新正确的数组,而无需遍历您可能拥有的所有不同组。 Here the example.

    【讨论】:

      【解决方案2】:

      我想出了这个答案:

        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;
      

      错误的结果是覆盖顶级属性并在没有标签的情况下重新创建它。不知道这里是否有更好的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-15
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        • 2012-11-11
        • 1970-01-01
        相关资源
        最近更新 更多