React-select 警告隐藏到不受控制

React-select warning hidden to uncontrolled

我在我的代码中使用了 react-select:

import React, {Component} from 'react';
import Select, {createFilter} from 'react-select';

let _ = require('underscore')

class Test extends Component {

  constructor(props) {
    super(props);
    this.state = {
      variables_api: [],
      selected_question_obj: null
    };
    this.handleChange_question = this.handleChange_question.bind(this)
  }

  componentDidMount() {
    fetch('http://127.0.0.1:5000/variables')
    .then(res => {
      return res.json()})
    .then(data => {
      this.setState({
        variables_api: data
      });
    })
  }

  handleChange_question(evt) {
    this.setState({
      selected_question_obj: evt
    });
  }

  render () {
    var key_api = this.state.variables_api.map(obj => {
      return {
        key_api: obj['index'],
        question_api: obj['Label Variabile'],
      };
    })
    var key = _.groupBy(key_api, 'question_api');

    var question_uni = Object.keys(key);
    var selector_q_options = []
    for (var i=0; i<question_uni.length; i++) {
      var temp_0 = {
        key: i.toString(),
        label: question_uni[i]
      };
      selector_q_options.push(temp_0)
    }

    console.log(this.state)

    return (
      <div>

      <Select
        name='question_selector'
        value={this.state.selected_question_obj}
        onChange={this.handleChange_question.bind(this)}
        options={selector_q_options}
        filterOption={createFilter({ignoreAccents: false})}
        placeholder='Select question:'/>

      </div>
    );
  };
}

export default Test

一切正常,期待这样的事实,当我 select 某些东西时,我收到这个警告:

A component is changing a controlled input of type hidden to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

如果我将 selected_question_obj 从 null 子 selected_question_obj 到 {},错误消失,但随后组件显示不正确(就像您已经 select 编辑了一些东西)。

你能帮帮我吗?如果您在代码中看到一些奇怪的东西,请记住我同时使用 js 和 React 还不到一个月,所以欢迎任何评论。谢谢!

尝试空字符串。不幸的是,对输入值使用 null 或 undefined 会导致该错误。这样的事情可能会奏效:

<Select
    name='question_selector'
    value={this.state.selected_question_obj || ""}
    onChange={this.handleChange_question.bind(this)}
    options={selector_q_options}
    filterOption={createFilter({ignoreAccents: false})}
    placeholder='Select question:'/>

您收到该错误的原因似乎是因为您传递给 <Select> 的选项不是正确的接口。看起来 react-select 调用 this helper function 从每个选项中获取值,它是 returns undefined

尝试将选项键的 "key" 更改为 "value"

for (var i=0; i<question_uni.length; i++) {
  var temp_0 = {
    key: i.toString(),       // should be 'value' instead of 'key'
    label: question_uni[i]
  };
  selector_q_options.push(temp_0)
}

对此:

for (var i=0; i<question_uni.length; i++) {
  var temp_0 = {
    value: i.toString(),      // changed to 'value'
    label: question_uni[i]
  };
  selector_q_options.push(temp_0)
}