0

所以,我有一个带有下拉列表的选择,其中包含 1 个默认答案。这是列表的代码:

renderPersonnel = (selectedRelationId: number) => HTML
${this.emptyPersonnelOption(!selectedRelationId)}
${this.personnel.map(
  ({id, name}) => 
     this.personnelSuggestionOption(id, name, selectedRelationId === Number(id)
  ))}

this.personnel由以下代码设置:

this.personnel = await fetch(getPersonnelByFunctionUrl(functionId))
            .then(response => response.json());
          // If the list does not contain the current relation, add the current relation if it exists
          if(this.shift.relation != null && !this.personnel.map(personnel => personnel.id).includes(this.shift.relation.id)) {
            this.personnel.push(this.shift.relation);
          }

最后一行会检查当前选择的选项是否为已删除的关系(它仍然存在于数据库中,但在提取人员时不会包含在内。因此这一行)。

这首先呈现默认选项,代码如下:

emptyPersonnelOption = (selected: boolean) => html    
<option value="" ?selected="${selected}">- Select person -</option>

加载此选择所在的页面时,一切都很好。所有相关选项都已加载,我可以选择这些选项并保存。但是,当我想取消选择一个选项并选择默认选项时,它会出错。它会在短时间内(约 1 秒)显示此选项,然后变为白色。

在浏览器中查看源码,发现多了一个空选项。

前:
前

后:
在此处输入图像描述

在上面的图片中,我从选择的第二个选项(Tim Batist)开始。我将此更改为默认选项(-选择人员-)。你可以看到这增加了第三个选项,它几乎是空的(除了值)。

问题:
当我在此选择中更改为默认选项时,我想查看默认选项。现在它将只显示一个空白字段。我已经尝试了一些事情,但我不知道问题可能是什么。

4

1 回答 1

0

看起来您正在设置一个类变量this.personnel,而不是使用 React 状态机制,这是正确触发更新所必需的。请参阅反应状态和生命周期。试试这样的代码:

${this.state.personnel.map(
  ({id, name}) => 
     this.personnelSuggestionOption(id, name, selectedRelationId === Number(id)
  ))}

//...

this.setState({personnel: await fetch(getPersonnelByFunctionUrl(functionId))
            .then(response => response.json())});

          // If the list does not contain the current relation, add the current relation if it exists
          if(this.shift.relation != null && !this.state.personnel.map(personnel => personnel.id).includes(this.shift.relation.id)) {
            this.state.personnel = [...this.state.personnel, this.shift.relation];
          }

您还需要this.state.personnel在构造函数中进行初始化,如下所示:

constructor() {
  this.state = {personnel: []};
}
于 2021-08-23T14:07:01.977 回答