首页 > 解决方案 > 搜索结果未推送到 MenuItem 下拉菜单

问题描述

我正在尝试将搜索功能中的结果(用户表中的用户名)推送到 MenuItem 下拉列表中。搜索功能正常工作并提取正确的结果,但我无法弄清楚为什么结果中的用户名没有显示在 MenuItem 中。

这是搜索当前用户列表并提取符合我需要的条件的用户,然后将这些结果推送到 MenuItem 的函数:

private getActiveLsList = () => {
 const opts = new Array<React.ReactElement<any>>();

 const sr = new SearchRequest();
 sr.addFilter("role", "LoanSpecialist");
 sr.addFilter("ls_status", "Active");

 searchUsers(this.props.app.api, sr).then((res: SearchResults<User>) => {
  if (!res || !res.numHits || res.numHits < 1 || !res.results) {
    opts.push(
      <Select key="0" value="0">
        "Error loading LS List"
      </Select>
    );

    return opts;
  }

  res.results.forEach(n => {
    opts.push(
      <MenuItem key={n.id} value={n.id}>
        <Typography> {n.userName} </Typography>
      </MenuItem>
    );
  });

  return opts;
 });
};

这是我调用 getActiveLsList 函数的地方(在渲染中):

       <TextField
          select
          fullWidth
          variant="outlined"
          value={this.state.assignedLS}
          onChange={this.updateAssignment("assigned_loan_specialist", "assignedLS")}
          margin="normal"
        >
          <MenuItem value="Unassigned">Unassigned</MenuItem>
          {this.getActiveLsList()}
        </TextField>

标签: reactjs

解决方案


我认为您至少需要像这样重新组织一下:

state = {
  activeLsList: null,
}

private getActiveLsList = () => {
  const opts = new Array<React.ReactElement<any>>();

  const sr = new SearchRequest();
  sr.addFilter("role", "LoanSpecialist");
  sr.addFilter("ls_status", "Active");

  searchUsers(this.props.app.api, sr).then((res: SearchResults<User>) => {
    if (!res || !res.numHits || res.numHits < 1 || !res.results) {
      opts.push(
        <Select key="0" value="0">
          "Error loading LS List"
        </Select>
      );
    } else {
      res.results.forEach(n => {
        opts.push(
          <MenuItem key={n.id} value={n.id}>
            <Typography> {n.userName} </Typography>
          </MenuItem>
        );
      });
    }
    // use setState to correctly refresh the component after returning from async function
    this.setState({ activeLsList: opts });
  });
};

render() {
  // check before triggering the async function to prevent infinite loop
  if (!this.state.activeLsList) this.getActiveLsList();

  return (
    <TextField
      select
      fullWidth
      variant="outlined"
      value={this.state.assignedLS}
      onChange={this.updateAssignment("assigned_loan_specialist", "assignedLS")}
      margin="normal"
    >
      <MenuItem value="Unassigned">Unassigned</MenuItem>
      {this.state.activeLsList} // render from this.state
    </TextField>
  );
}

推荐阅读