使用axios中的动态API路由,并使用输入在React中渲染表格。

huangapple go评论67阅读模式
英文:

Use dynamic api route in axios and use input to render a table in react

问题

我有一个应用程序,在该应用程序中,我正在使用一个API,该API需要具有动态路由(不确定是否使用了正确的术语)。使用该API,我需要从用户那里获取输入,并根据输入来呈现表格。

路由将如下所示:
URL = http://localhost:8080/creds?id={my_id}

我的代码如下:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const baseURL = "http://localhost:8080/creds?id=";

const Demo = () => {
    const [data, setData] = useState([]);
    const [input, setInput] = useState("");

    useEffect(() => {
        const getData = async (my_id) => {
            const endpoint = `${baseURL}${my_id}`;
            const response = await axios.get(endpoint);
            setData(response.data);
            console.log(data); // 这显示了输出的JSON,但我不能在useEffect之外使用它
        };
        getData(input);
    }, []);

    const handleInput = (e) => {
        let value = e.target.value;
        setInput(value);
    };

    const handleClick = () => {
        getData(input);
    }

    return (
        <div>
            <input type='text' value={input} onChange={handleInput} />
            <button onClick={handleClick}>search</button>
        </div>
    )
}

首先,出现的错误是我无法使用getData,TypeScript表示找不到它。如何在useEffect之外使用此函数?我想要使用我在 console.log(data) 中看到的JSON,但我不能按需使用它。

如果您需要更多澄清,请告诉我。

英文:

I have an app, where I'm using a API, which need to have dynamic route (not sure, if I'm using the right terminology), using that API, I need to get input from the user and based on the input, I have to render the table.

The route is going to be like,
URL = http://localhost:8080/creds?id={my_id}

My code is -

import React, { useState, useEffect } from &#39;react&#39;;
import axios from &#39;axios&#39;;

const baseURL = &quot;http://localhost:8080/creds?id=&quot;;

const Demo = () =&gt; {
    const [data, setData] : any = useState([]);
    const [input, setInput] : any = useState(&quot;&quot;);
    
 useEffect(() =&gt; {
        const getData = async (my_id) =&gt; {
            const endpoint = `${baseURL}${my_id}`;
            const response = await axios.get(endpoint)
            setData(response.data)
            console.log(data) // this shows the output json, but I cannot use it outside the useEffect
        };
        getData(input);
    }, []);

 const handleInput = (e: any) =&gt; {
        let value = e.target.value;
        setInput(value);
    };
 const handleClick = () =&gt; {
        getData(input)
    }

return (
     &lt;div&gt;
             &lt;input type=&#39;text&#39; value={input} onChange={handleInput} /&gt;
             &lt;button onClick={handleClick}&gt;search&lt;/button&gt;
     &lt;/div&gt;
    )
}

First error is I cannot use getData, ts says it cannot find it.
How to use this function, outside useEffect?
I want to use the json, which I can see when I
console.log(data)
I can't use it as I require.

If you need anymore clarifications, please let me know.

答案1

得分: 1

你犯了一个错误,你在useEffect回调内定义了getData,这将使你的函数只能在函数作用域内访问。

要解决这个问题,在useEffect回调之外定义这个函数,这样你就可以在组件的任何地方使用它。

英文:

you made a mistake, you defined getData inside of the useEffect callback and this makes your function only accessible within the function scope.

to solve the problem define the function outside the useEffect callback and you'll be able to use it anywhere in the component.

答案2

得分: 0

有很多地方出现了问题。
我已经创建了一个名为 http-common.ts 的文件,其中包含 axios.create。 axios.create 方法允许您创建具有默认配置选项的自定义 Axios 实例。

apiService.ts 文件中为所有 API 发出了请求,并为所有所需的有效负载创建了类型。API 是 GraphQL API。与之互动相对容易。不需要在 useEffect 钩子中发出请求。

如果有任何类似的疑问,欢迎留下您的评论。我会乐意回答。

英文:

There were so many things wrong with the approach.
I have created a http-common.ts file, which contains axios.create. The axios.create method allows you to create a customized Axios instance with default configuration options.

Made the requests for all the APIs in apiService.ts file. And created type for all payload required. API was graphQL API. It was kind of easy to interact it with. Didn't need to make request in useEffect hook.

If anyone has any similar doubt, leave your comments. I'll be happy to answer.

huangapple
  • 本文由 发表于 2023年4月11日 05:06:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定