javascript - 在选项可以填充之前呈现 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}
/>
解决方案
第一个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 }));
}
推荐阅读
- vba - 多行VBA
- python - Python Flask-sqlAlchemy Prepapre 查询
- python - 名称事件未定义
- javascript - 基于javascript数组更改背景图片url
- django - 我想登录后进入默认页面(“/”)(django视图问题)
- sql-server - 将 SQL Server 游标转换为 Azure Synapse
- c# - Microsoft Bot Framework V4:System.NullReferenceException:'无法在 HostContext 中找到 SkillConversationIdFactoryBase'
- rdf - 使用类或概念来建模枚举
- javascript - 在 Laravel 中,如何简单地将数据从 js 传递到控制器返回查看?
- r - 从 pheatmap 中的 cutree_rows 组中提取基因/观察值