【发布时间】:2021-09-27 13:04:06
【问题描述】:
我相信我误解了状态在 React 中是如何工作的。我有一个 TextField 作为 Material UI Autocomplete 组件的一部分。每次文本更改以使用新值搜索 API 时,该页面都应该获取新结果。底部的简单输出列表按预期更新,但列表自动完成组件中从未填充任何结果。 Here 是自动完成通常应该如何工作,这是我的代码 (Sandbox link)。
我的问题是
- 如果下面的标签有,为什么 TextField 在初始加载时没有文本值“篮球”?
- 我对 inputText 和 setOptions 的依赖是加载数据的最佳方式吗?
最终我想获取书籍列表,仅限于前 N 个结果,并使用从 JSON 结果返回的数据填充表单的其余部分。
谢谢!
<Autocomplete
id="ac1"
options={options}
onInputChange={(event, newValue) => { // text box value changed
console.log("onInputChange start");
setInputText(newValue);
// if ((newValue).length > 3) { setInputText(newValue); }
// else { setOptions([]); }
console.log("onInputChange end");
}}
// SHOW THE TITLE IF THERE IS ONE
getOptionLabel={(option) => option.volumeInfo && option.volumeInfo.title ? option.volumeInfo.title : "Unknown Title"}
style={{ width: 600 }}
renderInput={(params) =>
<>
<TextField {...params} label="Search for a book" variant="outlined"
//ISBN - 10 or 13 digit
value={inputText} // *** I WOULD EXPECT THIS TO BE SET TO "BASKETBALL" ON FIRST RENDER
InputProps={{
...params.inputProps
}}
/>
</>}
/>
useEffect(() => {
async function fetchData() {
const fetchString = `https://www.googleapis.com/books/v1/volumes?maxResults=3&q=${inputText}&projection=lite`;
console.log(fetchString);
const res = await fetch(
fetchString,
);
const json = await res.json();
// set the options to
(json && json.items) ? setOptions(json.items) : setOptions([]);
}
console.log("fetching data");
fetchData();
console.log("fetched data");
}, [inputText, setOptions]);
【问题讨论】:
标签: reactjs react-hooks material-ui