Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

reactjs - How to force Material UI Autocomplete to show suggestions after they are loaded?

When using Material UI Autocomplete (https://material-ui.com/components/autocomplete/), an input is created and suggestions are to be displayed:

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

const options = ['Option 1', 'Option 2'];

export default function ControllableStates() {
  ...

  return (
    ...
      <Autocomplete
        onInputChange={(event, newInputValue) => {
          if (newInputValue.length < 3) return;
          // UPDATING OPTIONS
          options.length = 0;
          getNewOptions(newInputValue).forEach((item) => options.push(item)):
        }}
        options={options}
        ...
        renderInput={(params) => <TextField {...params} />}
      />
    ...
  );
}

But what happens actually is that getNewOptions is executed, options are updated, but suggestions list does not display. But when i type 'xyz', and then press backspace suggestion list shows up with data from last getNewOptions execution.

So it seems that when I load data in onInputChange there is some kind of a race condition causing the suggestion list to not show up. How to force suggestions to show up after I update options?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using options as a state, and instead of pushing to options, use the 'setState' method to update this value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...