简体   繁体   English

React.JS:进行获取以填充 select

[英]React.JS : make fetch to populate select

I'm trying to make a fetch to populate my select, but I can't use the fetch..我正在尝试进行提取以填充我的 select,但我无法使用提取..

const loadOptions = async (searchQuery, loadedOptions, { page }) => {
    const requestMethod = {
                method: "PUT",
                headers: { 'Content-Type': 'application/json' },
                body: { realmIds: [props.realmScelto] }
            };
    
            const response = await fetch('myapi', requestMethod) // error is here, in requestMethod

            // const response = await axios.post(`myapi?page=${page}&size=20`, { realmIds: [props.realmScelto] }) // this works.. it gives me back 1 value, and it ok but add always the same value that I obtain from api

            // const optionToShow = await response.data
            const optionToShow = await response.json()
 return {
            options: optionToShow,
            hasMore: optionToShow.length >= 1,
            additional: {
                page: searchQuery ? 2 : page + 1,
            },
        };
    };

    const onChange = option => {
        if (typeof props.onChange === 'function') {
            props.onChange(option);
        }
    };

    return (
        <AsyncPaginate
            value={props.value}
            loadOptions={loadOptions}

            onChange={onChange}
            isSearchable={true}
            placeholder="Select"
            additional={{
                page: 0,
            }}
        />
    );

The error that I receive in the requestMethod is:我在 requestMethod 中收到的错误是:

The argument of type '{method: string; '{method: string; 类型的参数headers: {'Content-Type': string;标头:{'Content-Type':字符串; }; }; body: {realmIds: any [];身体:{realmIds:任何[]; }; }; } 'is not assignable to the parameter of type' RequestInit '. ' ' 不可分配给' RequestInit ' 类型的参数。 The types of the 'body' property are incompatible. “body”属性的类型不兼容。 The type '{realmIds: any [];类型 '{realmIds: any []; } 'is not assignable to type' BodyInit '. ' ' 不可分配给类型' BodyInit '。 In type '{realmIds: any [];在类型 '{realmIds: any []; } 'The following properties of type' URLSearchParams' are missing: append, delete, get, getAll and 4 more. '以下类型为'URLSearchParams'的属性缺失:append、delete、get、getAll 和另外 4 个。

For fetch , the body you pass in is not converted to JSON automatically.对于fetch ,您传入的body不会自动转换为 JSON 。

Try尝试

const requestMethod = {
    method: "POST",
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ realmIds: [props.realmScelto] })
};
const response = await fetch(`myapi?page=${page}&size=20`, requestMethod)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM