ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

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

ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

问题

我遇到了一个问题,当我调用"map"函数来遍历使用useState创建的对象数组时,我收到一个错误消息说"map"不是一个函数。

如果我在手动定义的数组上使用它,比如const array = [a, b, c],它就能正常工作,但是在使用useState时就不行了。

我像这样创建了数组(请注意,我只粘贴了实际执行此操作的部分):

// 其他代码

async function getFicharpgs(login_usuario) {
    // 步骤1 - 从API获取我的JSON数据。
    try {
        const response = await axios({
            method: "post", url: "http://localhost:3000/usuario_ficharpg/listar_fichas", data: {"login": login_usuario}
        });

        // 控制台日志完美打印(如下图所示。)
        console.log('getFicharpgs => Resposta completa:', response);
        console.log('getFicharpgs => Lista de Fichas do Usuário Recebida:', response.data);

        return response; // 这里返回我的响应数据,包括我的JSON数据。

// 其他代码

function Ficharpg({objeto_props}) {
    const {login_usuario} = objeto_props;

    // 步骤2 - 将我的数组列表作为状态变量创建,以便传递给另一个组件
    const [ficharpgs, setFicharpgs] = useState([]);

// 其他代码

useEffect(() => {
        // 步骤3 - 将从getter获取的数据传递给我的useState数组。
        if (login_usuario) {
            // 等待异步函数getUsers完成后再结束效果(渲染组件)。
            getFicharpgs(login_usuario)
                // 使用Then/Catch实现“Promise Ignored”并制定业务规则。
                .then(response => {
                    // 如果我们的状态是200,就会进入这里 - [Object object]
                    console.log(`Componente Ficharpg => Fichas de RPG do Usuario Recebidas com sucesso. Status: ${response.status}`);

                    // 更改状态以指示数据加载完成
                    setdadosCarregando(false);

                    // 这里是将响应中的数据添加到状态变量的地方。
                    setFicharpgs(response.data);  // 第3步在这里完成。

// 其他代码

// 渲染来自我的useState数组的数据。
return (<div>
    {/* 条件运算符检查数据是否正在加载。 */}
    {dadosCarregando ? (<p>Selecione qual usuário vai mostrar as fichas.</p>) : (<table>
        <thead>
        <tr>
            <th>Fichas de RPG do Usuario {login_usuario}</th>
        </tr>
        <tr>
            <th>Nome</th>
            <th>Classe</th>
            <th>Raca</th>
            <th>Nivel</th>
            <th>Alinhamento</th>
        </tr>
        </thead>
        <tbody>

        {/* 步骤4 - 遍历我的列表并打印我的对象。 */}
        {ficharpgs.map((ficharpg, ficharpg_id) => (
            // 索引键:RPG表格的ID,我们的“行”(Table Row)的标识符 - Key => JavaScript的内置功能。
            <tr key={ficharpg_id}>
                <td>name: {ficharpg.nome}</td>{" "}
                <td>age: {ficharpg.classe}</td>
                <td>age: {ficharpg.raca}</td>
                <td>age: {ficharpg.nivel}</td>
                <td>age: {ficharpg.alinhamento}</td>
            </tr>
        ))}

// 其他代码

所以,在第4步,我希望它会打印出我的数组中的数据,但是相反,我得到了以下错误:

ficharpgs.map 不是一个函数
TypeError: ficharpgs.map 不是一个函数

我已经尝试过查看其他用户遇到相同问题的帖子,比如这个:

https://stackoverflow.com/questions/57994107/reactjs-usestate-map-is-not-a-function

但我无法通过阅读它的答案来解决它。 ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

编辑

快速编辑一下,这是从我的getter函数内部打印响应本身的控制台日志输出:

ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

这是从我的组件内部打印我的useState数组的控制台日志输出:

ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

英文:

I am experiencing a problem that when I call the "map" function to iterate over a array of objects that was created using useState, I get a error saying that "map" is not a function.

It works fine if I use it on a manuually defined array like `const array = [a, b, c] but when using useState, it does not.

I created the array like this (Notice that I only pasted the parts that are actually doing this.)

// Etc

async function getFicharpgs(login_usuario) {
    // Step 1 - Get my JSON Data from my API.
    try {
        const response = await axios({
            method: &quot;post&quot;, url: &quot;http://localhost:3000/usuario_ficharpg/listar_fichas&quot;, data: {&quot;login&quot;: login_usuario}
        });

        // Console Log prints perfectly (Printed image below.)
        console.log(&#39;getFicharpgs =&gt; Resposta completa:&#39;, response);
        console.log(&#39;getFicharpgs =&gt; Lista de Fichas do Usu&#225;rio Recebida:&#39;, response.data);

        return response; // This returns my response data, including my JSON Data.

// Etc

function Ficharpg({objeto_props}) {
    const {login_usuario} = objeto_props;

    // Step 2 - Create my array list as a state variable to be passed on to another component
    const [ficharpgs, setFicharpgs] = useState([]);

// Etc

useEffect(() =&gt; {
        // Step 3 - Pass the data I got from my getter to my useState array.
        if (login_usuario) {
            // Espera a fun&#231;&#227;o ass&#237;ncrona getUsers ser conclu&#237;da antes de finalizar o efeito (Renderizar o Componente).
            getFicharpgs(login_usuario)
                // Implantacoes de Then/Catch para resolver &quot;Promise Ignorada&quot; e fazer regras de negocio.
                .then(response =&gt; {
                    // Entra aqui caso o nosso status tenha sido 200 - [Object object]
                    console.log(`Componente Ficharpg =&gt; Fichas de RPG do Usuario Recebidas com sucesso. Status: ${response.status}`);

                    // Mudo o estado para dizer que o carregamento dos dados terminou
                    setdadosCarregando(false);

                    // Here is where I add my data from my response into the state variable.
                    setFicharpgs(response.data);  // Step 3 Completed here.

// Etc

    // Render the data from my useState array.
    return (&lt;div&gt;
        {/* If Ternario que checa se os dados estao sendo carregados. */}
        {dadosCarregando ? (&lt;p&gt;Selecione qual usu&#225;rio vai mostrar as fichas.&lt;/p&gt;) : (&lt;table&gt;
            &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;Fichas de RPG do Usuario {login_usuario}&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;th&gt;Nome&lt;/th&gt;
                &lt;th&gt;Classe&lt;/th&gt;
                &lt;th&gt;Raca&lt;/th&gt;
                &lt;th&gt;Nivel&lt;/th&gt;
                &lt;th&gt;Alinhamento&lt;/th&gt;
            &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;

            {/* Step 4 - Iterate over my list and print my objects. */}
            {ficharpgs.map((ficharpg, ficharpg_id) =&gt; (
                // Index Key: ID da Ficha do RPG, identificador da nossa &quot;linha&quot; (Table Row) - Key =&gt; Built-In Do JavaScript.
                &lt;tr key={ficharpg_id}&gt;
                    &lt;td&gt;name: {ficharpg.nome}&lt;/td&gt;{&quot; &quot;}
                    &lt;td&gt;age: {ficharpg.classe}&lt;/td&gt;
                    &lt;td&gt;age: {ficharpg.raca}&lt;/td&gt;
                    &lt;td&gt;age: {ficharpg.nivel}&lt;/td&gt;
                    &lt;td&gt;age: {ficharpg.alinhamento}&lt;/td&gt;
                &lt;/tr&gt;
            ))}

// Etc

So, at step 4, I was expecting it to print my data from the array, but instead, I am getting the following error:

> ficharpgs.map is not a function
> TypeError: ficharpgs.map is not a function

I already tried to look into another posts from users that had the same problems, like this one:

https://stackoverflow.com/questions/57994107/reactjs-usestate-map-is-not-a-function

But I was not able to fix it reading the answer from it. ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

Edit

Just a quick edit, here is the output of a console.log from inside my getter function that prints the response itself:

ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

And this is the output of a console.log from inside my component, that prints my useState array:

ReactJS: JavaScript "Map" function says "is not a function" when trying to iterate on a "useState" array of objects

答案1

得分: 2

这是一个常见的错误,当你引用的变量不是一个数组时就会发生。

map() 是数组的一个方法,所以如果变量不是一个数组,它会抛出这个错误。

正如你的截图所示,getFicharpgs() API 调用的响应是一个对象,而不是一个数组。

所以,你需要获取正确的数组:

getFicharpgs(login_usuario)
  .then(response =&gt; {
    // ...
    setFicharpgs(response.data.ficas_do_usuario);
英文:

This is a common error that happens when the variable you referred to is not an array.

map() is a method of an array, so if the variable is not an array, it will throw this error.

As your screenshot says, the response of getFicharpgs() API call is an object, not an array.

So, you need to get the correct array:

getFicharpgs(login_usuario)
  .then(response =&gt; {
    // ...
    setFicharpgs(response.data.ficas_do_usuario);

huangapple
  • 本文由 发表于 2023年6月13日 02:58:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459540.html
匿名

发表评论

匿名网友

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

确定