如何在ReactJS中从API响应中显示选择下拉框

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

How do I show select dropdown from an API response in ReactJS

问题

以下是翻译好的代码部分:

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

const getProjects = () => {
    axios.get('/api/projects', {
        header: {
            Authorization: 'Bearer ' + localStorage.getItem('token')
        }
    })
    .then((res) => {
        return res.data
    })
    .catch((ex) => {
        console.log(ex)
    })
}

const Dropdown = () => {
    
    const [projects, setProjects] = useState([])

    useEffect(() => {
        getProjects()
    })

    return(
        <div>
                       
        </div>
    )
}

export default Dropdown

编辑后的代码:

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

const getProjects = () => {
    axios.get('/api/projects', {
        header: {
            Authorization: 'Bearer ' + localStorage.getItem('token')
        }
    })
    .then((res) => {
        return res.data
    })
    .catch((ex) => {
        console.log(ex)
    })
}

const Dropdown = () => {
    
    const [projects, setProjects] = useState([])    

    useEffect(() => {
        getProjects(setProjects)
    }, [])

    return(
        <div>
            <label htmlFor="select">Class Name</label>
            <select>
                {projects.map(project => {
                    return <option key={project.id} value={project.id}>{project.name}</option>
                })}
            </select>                       
        </div>
    )
}

export default Dropdown

请注意,这段代码仍然有一些问题,可能需要进一步调试和修复。如果您需要更多帮助,请随时提出具体的问题。

英文:

I have a function that gets a list of projects from a MOCK API and I wish to get the projects list and list them inside a select dropdown using React. This is what I've tried and I've gotten stuck. Please don't be mean with the responses, I'm still new as a React Developer and I am learning as I go.

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

const getProjects = () =&gt; {
    axios.get(&#39;/api/projects&#39;, {
        header: {
            Authorization: &#39;Bearer &#39; + localStorage.getItem(&#39;token&#39;)
        }
    })
    .then((res) =&gt; {
        return res.data
    })
    .catch((ex) =&gt; {
        console.log(ex)
    })
}

const Dropdown = () =&gt; {
    
    const [projects, setProjects] = useState([])

    useEffect(() =&gt; {
        getProjects()
    })

    return(
        &lt;div&gt;
                       
        &lt;/div&gt;
    )
}

export default Dropdown

I've iterated through a couple of solutions and they all aren't working. The API sits here
MOCK API

EDIT
this is how far I've progressed with the suggestions

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

const getProjects = () =&gt; {
    axios.get(&#39;/api/projects&#39;, {
        header: {
            Authorization: &#39;Bearer &#39; + localStorage.getItem(&#39;token&#39;)
        }
    })
    .then((res) =&gt; {
        return res.data
    })
    .catch((ex) =&gt; {
        console.log(ex)
    })
}

const Dropdown = () =&gt; {
    
    const [projects, setProjects] = useState([])    

    useEffect(() =&gt; {
        getProjects(setProjects)
    }, [])

    return(
        &lt;div&gt;
            &lt;label htmlFor=&quot;select&quot;&gt;Class Name&lt;/label&gt;
            &lt;select&gt;
                {projects.map(project =&gt; {
                    return &lt;option key={project.id} value={project.id}&gt;{project.name}&lt;/option&gt;
                })}
            &lt;/select&gt;                       
        &lt;/div&gt;
    )
}

export default Dropdown

答案1

得分: 1

以下是翻译好的部分:

不改变状态也不对从AJAX请求返回的值做任何操作您需要使用类似这样的代码

```jsx
import React, { useEffect, useState } from "react";
import axios from "axios";

const getProjects = (done) => {
    axios.get('/api/projects', {
        header: {
            Authorization: 'Bearer ' + localStorage.getItem('token')
        }
    })
    .then((res) => {
        done(res.data);
    })
    .catch((ex) => {
        console.log(ex);
    });
};

const Dropdown = () => {
    
    const [projects, setProjects] = useState([]);

    useEffect(() => {
        getProjects(setProjects);
    });

    
    return (
      <div>
        <select>
         {projects.map(project => {
            return (
              <option key={project.id} value={project.id}>
                {project.name}
              </option>
            );
         })}
        </select>
       </div>
    );
};

export default Dropdown

还需要添加以下代码:

    useEffect(() => {
        getProjects(setProjects);
    }, []);

这样,AJAX请求仅在组件挂载时执行,而不是在每次更新时执行(可能会导致无限循环)。

您还可以将获取数据的操作封装成自定义钩子:

const useProjects = () => {
    const [projects, setProjects] = useState([]);

    useEffect(() => {
      axios.get('/api/projects', {
        header: {
            Authorization: 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then((res) => {
        setProjects(res.data);
      })
      .catch((ex) => {
        console.log(ex);
      });
    }, []);

    return projects;
};

const Dropdown = () => {
    const projects = useProjects();
    
    return (
      <div>
        <select>
         {projects.map(project => {
            return (
              <option key={project.id} value={project.id}>
                {project.name}
              </option>
            );
         })}
        </select>
       </div>
    );
};

<details>
<summary>英文:</summary>

You don&#39;t change the state and you do nothing with the value returned from the AJAX request. You need to use something like this:

```jsx
import React, { useEffect, useState } from &quot;react&quot;;
import axios from &quot;axios&quot;;

const getProjects = (done) =&gt; {
    axios.get(&#39;/api/projects&#39;, {
        header: {
            Authorization: &#39;Bearer &#39; + localStorage.getItem(&#39;token&#39;)
        }
    })
    .then((res) =&gt; {
        done(res.data);
    })
    .catch((ex) =&gt; {
        console.log(ex);
    });
};

const Dropdown = () =&gt; {
    
    const [projects, setProjects] = useState([]);

    useEffect(() =&gt; {
        getProjects(setProjects);
    });

    
    return (
      &lt;div&gt;
        &lt;select&gt;
         {projects.map(project =&gt; {
            return (
              &lt;option key={project.id} value={project.id}&gt;
                {project.name}
              &lt;/option&gt;
            );
         })}
        &lt;/select&gt;
       &lt;/div&gt;
    );
};

export default Dropdown

You also need:

    useEffect(() =&gt; {
        getProjects(setProjects);
    }, []);

So the AJAX request happens only on the component mount and not on every update (which may cause an infinite loop).

You can also make the fetch into a custom hook:

const useProjects = () =&gt; {
    const [projects, setProjects] = useState([]);

    useEffect(() =&gt; {
      axios.get(&#39;/api/projects&#39;, {
        header: {
            Authorization: &#39;Bearer &#39; + localStorage.getItem(&#39;token&#39;)
        }
      })
      .then((res) =&gt; {
        setProjects(res.data);
      })
      .catch((ex) =&gt; {
        console.log(ex);
      });
    }, []);

    return projects;
};

const Dropdown = () =&gt; {
    const projects = useProjects();
    
    return (
      &lt;div&gt;
        &lt;select&gt;
         {projects.map(project =&gt; {
            return (
              &lt;option key={project.id} value={project.id}&gt;
                {project.name}
              &lt;/option&gt;
            );
         })}
        &lt;/select&gt;
       &lt;/div&gt;
    );
};

答案2

得分: 0

Sure, here is the translation of the provided text:

your code contain more errors

  1. 函数 getProject 仍在等待响应,当使用 return 时将得到未定义或空值。
  2. 在 useEffect 中,您将会遇到错误,因为项目会无限运行。
  3. 调用函数后,请确保将响应数据放在正确的位置。

要纠正您的代码并使其正常工作,必须遵循以下提示

  1. 将函数 getProject 转换为 Promise。
  2. 使用此语句 useEffect(function(){},[]) 以便只调用一次。
  3. 如果您使用 Promise 获取项目,则将响应数据放在正确的位置,使用 setProject(data.response)。

> 如果您仍有任何问题或需要帮助,我在这里,您必须通知我,如果您需要纠正代码。

英文:

your code contain more errors

  1. function getProject is still wait response the when use return will get undefined or null
  2. in useEffect you will give you error,because have unlimited run project
  3. after call function dont put data response in right place

for correct your code and working must follow this tips

  1. function getProject convert him to Promise

  2. use this sentence useEffect(function(){},[]) for calling at once

  3. if you use promise getProject then put data response in right place setProject(data.response)

> if you still have any question or help i'm here you must notify me also if you need correct code

huangapple
  • 本文由 发表于 2023年6月27日 19:09:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564251.html
匿名

发表评论

匿名网友

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

确定