反应选择异步选项,

Bom*_*ber 1 reactjs react-select

我正在尝试将此组件与使用es5的异步选项一起使用。我的componentDidmount中有一个服务调用,该调用使用回调设置school数组:

componentDidMount: function(){

    SchoolsDataService.getSchools(
        this.setSchoolsState
    );
Run Code Online (Sandbox Code Playgroud)

将学校列表设置为状态数组

setSchoolsState: function(data){

    this.setState({schools: data.schools})

},
Run Code Online (Sandbox Code Playgroud)

服务:

getSchools: function (callback) {

    var url = 'xxxx';

    request
        .get(url)
        .set('Accept', 'application/json')
        .end(function (err, res) {
            if (res.ok) {
                var data = res.body;
                if (data) {
                    callback(data);
                }
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

如何使用文档中的示例进行设置?我在哪里将这样的异步版本的服务调用放在哪里并生成选项列表?

var getOptions = function(input, callback) {
setTimeout(function() {
    callback(null, {
        options: [
            { value: 'one', label: 'One' },
            { value: 'two', label: 'Two' }
        ],
        // CAREFUL! Only set this to true when there are no more options,
        // or more specific queries will not be sent to the server.
        complete: true
    });
}, 500);
};
Run Code Online (Sandbox Code Playgroud)

我的组件使用以下方式渲染:

  <Select.Async
         name="form-field-name"
         value="one"
         loadOptions={getOptions}/>
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

未捕获的不变违规:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。检查的渲染方法TableModalComponent

我在页面顶部:

Select = require('react-select'),
Run Code Online (Sandbox Code Playgroud)

pie*_*d_2 5

我认为您在这里有2种不同的选择:

您要么继续在componentDidMount中进行服务调用,该服务会更新本地状态,然后就不需要异步选项,因为您可以直接将options = {this.state.schools}传递给选择组件,

或者您不需要本地状态(也不需要componentDidMount服务调用),因为您可以直接在getOptions函数中进行服务调用(对于async-options select-component):

var getOptions = function(input, callback) {
    setTimeout(function() {
        SchoolsDataService.getSchools(function(data) {
            callback(null, {
                options: data.schools,
                complete: true,
            });
        });
    }, 500);
};
Run Code Online (Sandbox Code Playgroud)