首页 > 解决方案 > React-Select:如何在加载选项时显示“正在加载...”

问题描述

我正在尝试为我的 WordPress 块组件使用“React-Select”来选择帖子类别。
我想要的是在加载类别时显示“正在加载...”,然后在加载完成时显示类别列表或“未找到类别”。
使用我的代码,它在加载时显示“未找到类别”,然后显示类别列表。

export default class Categories extends Component {
    constructor() {
        super( ...arguments );
        this.state = {cats: []};
    }
    componentDidMount () {
        return apiFetch({path: '/myoriginal-blocks/v1/categories'})
        .then(data => {
            this.setState({cats:data});
        })
    }
    onChangeCategories = newCategories => {
        this.props.setAttributes({ category: newCategories == null ? [] : newCategories });
    }
    render() {
        const { attributes } = this.props;
        const { category } = attributes;
        return (
            <>
                <div>
                    <label>Categories</label>
                    <Select
                        isMulti
                        isClearable
                        placeholder='Search categories...'
                        onChange={ this.onChangeCategories }
                        options={ this.state.cats }
                        value={ category && category }
                        noOptionsMessage={() => 'No Categories Found'}
                    />
                </div>
            </>
        );
    }
}

在此处输入图像描述

或者也许我必须使用“Async-Select”而不是“React-Select”,但我不能很好地理解它的文档。
https://react-select.com/async
希望有人帮助我。谢谢你。

标签: reactjswordpress-gutenberg

解决方案


你可以isLoading支持 react-select 组件。

在您的状态中添加一个属性来管理加载

this.state = {cats: [], isLoading: true};

然后设置 isLoading false

return apiFetch({ path: "/myoriginal-blocks/v1/categories" }).then(
      (data) => {
        this.setState({ cats: data, isLoading: false });
      }
    );

并在 Select 组件中传递 isLoading 道具

<Select
    isMulti
    isClearable
    placeholder='Search categories...'
    onChange={ this.onChangeCategories }
    options={ this.state.cats }
    value={ category && category }
    noOptionsMessage={() => 'No Categories Found'}
    isLoading={this.state.isLoading}
/>

推荐阅读