【问题标题】:State not applied as expected when fetching data from API从 API 获取数据时未按预期应用状态
【发布时间】:2021-09-27 13:04:06
【问题描述】:

我相信我误解了状态在 React 中是如何工作的。我有一个 TextField 作为 Material UI Autocomplete 组件的一部分。每次文本更改以使用新值搜索 API 时,该页面都应该获取新结果。底部的简单输出列表按预期更新,但列表自动完成组件中从未填充任何结果。 Here 是自动完成通常应该如何工作,这是我的代码 (Sandbox link)。

我的问题是

  1. 如果下面的标签有,为什么 TextField 在初始加载时没有文本值“篮球”?
  2. 我对 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


    【解决方案1】:

    试试这个

    <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。我是否误解了这些应该如何工作?理想情况下,我希望能够将 InputProps 的原始计划、进度指示器等放入其中。
    • 我的整个事情都是基于官方文档中的代码。 material-ui.com/components/autocomplete/#asynchronous-requests
    【解决方案2】:

    感谢@Ignacio Elias 让我走到了一半,非常感谢。

    我很遗憾地说(在我的职业生涯中第 1000 次)这真的是,真的愚蠢。在下面代码的第二行中,我需要将展开运算符中的 InputProps 大写,因为虽然 inputProps a valid property of TextField,但它不是我想要的。 我将“inputProps”更改为“InputProps”,我现在很好。我正在混合道具 InputProps 和 inputProps。这两个都作为有效的道具存在真是太疯狂了。

                           InputProps={{
                                ...params.inputProps, // <----- RIGHT HERE
                                //autoComplete: 'new-password', // forces no auto-complete history
                                endAdornment: (
                                    <InputAdornment position="end" color="inherit">
                                        {/* className={classes.adornedEnd} */}
                                        {/* {loading ? */}
                                        <CircularProgress color="secondary" size={"2rem"} />
                                        {/* : null} */}
                                    </InputAdornment>
                                ),
                                style: {
                                    paddingRight: "5px"
                                }
                            }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多