首页 > 解决方案 > 在选项可以填充之前呈现 React-Select

问题描述

我在react-select这里找到:https ://react-select.com/home#welcome

我的下拉列表当前为空,我相信 select 元素在 setState 发生之前被渲染。我在文档中看到他们有async组件,但不确定如何转换我的代码来解决这个问题。

这是我的代码:

async GetFlavors() {
    let preprocessedData;
    try {
        let getFlavors1 = [
            { value: 'chocolate', label: 'Chocolate' },
            { value: 'strawberry', label: 'Strawberry' },
            { value: 'vanilla', label: 'Vanilla' }
            ]

        console.log(getFlavors1);

            this.setState({ getFlavors: [...getFlavors1] });    
            console.log(this.state.getFlavors); 

    } catch(error) {

    }

    return preprocessedData;

}

async componentDidMount() {
    await this.GetFlavors();
}

<label className="form-label">
    Flavors:
</label>
<Select
    value={this.state.flavors}
    onChange={this.handleChangeFlavors}
    options={this.state.getFlavors}
/>  

标签: javascriptreactjsasynchronousreact-select

解决方案


第一个render()发生 componentDidMount运行之前。您可以通过搜索来确认这一点react component lifecycle

解决方案是在渲染任何使用数据的组件之前检查数据是否存在。这可以通过多种方式完成,这里我这样做{data && <Component>}

{this.state.getFlavors &&
    <Select
        value={this.state.flavors}
        onChange={this.handleChangeFlavors}
        options={this.state.getFlavors}
    />
}

另请注意:我不确定是否componentDidMount可以与async前缀一起使用。在内部使用 Promise 的解决方案componentDidMount通常如下所示:

componentDidMount() {
    fetch("your url")
        .then(res => res.json())
        .then(json => this.setState({ data: json }));
}

推荐阅读