从下拉列表中选择值后,React Material UI 自动完成,防止 OnInputChange

mat*_*th5 3 reactjs material-ui

当人们从下拉列表中选择一个选项时,如何防止 React Material UI 不触发 onInputChange?使用下拉菜单后,它会再次重新触发 API,这是我试图阻止的。

    <Autocomplete
      options={patientOptions}
      onChange={(_event, newValue) => {
        onPatientChange(newValue);
      }}
      noOptionsText={
        <Typography>
          <Box color="text.hint">
            {patientLength === 0
              ? 'Type at least 1 character to search'
              : 'No results found.'}
          </Box>
        </Typography>
      }
      onInputChange={async (
        event: object,
        value: string,
        reason: string,
      ) => {
        setPatientLength(value.length);
        if (value.length > 0) {
          await getPatient(value, undefined).then(x => {
            setPatientOptions(x.patients);
          });
        }
      }}
      getOptionLabel={option => getPatientLabel(option)}
      renderInput={params => (
        <TextField
          value={patientValue}
          {...params}
        />
      )}
    />
Run Code Online (Sandbox Code Playgroud)

mor*_*ney 5

为了防止在用户从下拉列表中选择选项时进行 API 调用,您可以查阅reason的参数onInputChangereason始终会在reset用户选择选项和input输入自定义文本时发生。在后一种情况下,您还应该检查自定义文本是否包含在patientOptions.

我已将以下条件添加到您的条件逻辑中onInputChangereason === 'input' && !patientOptions.find(value)

    <Autocomplete
      options={patientOptions}
      onChange={(_event, newValue) => {
        onPatientChange(newValue);
      }}
      noOptionsText={
        <Typography>
          <Box color="text.hint">
            {patientLength === 0
              ? 'Type at least 1 character to search'
              : 'No results found.'}
          </Box>
        </Typography>
      }
      onInputChange={async (
        event: object,
        value: string,
        reason: string,
      ) => {
        setPatientLength(value.length);
        if (value.length > 0 && reason === 'input' && !patientOptions.find(value)) {
          await getPatient(value, undefined).then(x => {
            setPatientOptions(x.patients);
          });
        }
      }}
      getOptionLabel={option => getPatientLabel(option)}
      renderInput={params => (
        <TextField
          value={patientValue}
          {...params}
        />
      )}
    />
Run Code Online (Sandbox Code Playgroud)