简体   繁体   English

为什么 data.map 不是 function?

[英]Why is data.map not a function?

I built the following component in React:我在 React 中构建了以下组件:

import React, { useState } from 'react';


export default function Exemple(){

    var friend = function (id, firstName, lastName){
        this.id = id; this.firstName = firstName; this.lastName = lastName
    }

    var [data, setData] = useState( [
        new friend(1, 'jon', 'well')
    ])

    var newFriend =  new friend();

    function addFriend(e){  
        newFriend[e.target.id] = e.target.value;
    }

    function saveFriend(){
        setData(data.push(newFriend));
    }

    return( 
    <div className="my-table-friends">
         <table className="table">
    <thead>
      <tr>
        <th className="my-table-th">id</th>
        <th className="my-table-th">first name</th>
        <th className="my-table-th">last name</th>
      
      </tr>
    </thead>
        <tbody>
          
            {data.map((d)=>{return(
                <tr>
                    <td>{d.id}</td>
                    <td>{d.firstName}</td>
                    <td>{d.lastName}</td>
                </tr>)
            })}
        </tbody> 
  </table>

  

    <form>
    <label for="fname">id</label><br />
    <input type="text" id="id" name="fname" onChange={addFriend}/><br />
    <label for="fname">first name</label><br />
    <input type="text" id="firstName" name="fname" onChange={addFriend} /><br />
    <label for="lname">last name</label><br />
    <input type="text" id="lastName" name="lname" onChange={addFriend}/><br />
    <button onClick={saveFriend}>add</button>
    </form>
 
    </div>)
}

There is a table of friends here, and a form for adding friends.这里有一张朋友表,还有一个添加朋友的表格。 The table gets its data from the 'data' array and displays it using the map function.该表从“数据”数组中获取数据,并使用 map function 显示它。 For some reason, when I update the array the array becomes an object, and gets an error that data.map is not a function.出于某种原因,当我更新数组时,数组变为 object,并得到一个错误,即 data.map 不是 function。 What is the explanation for this?对此有何解释?

You're mutating the state and setting it to integer.您正在改变 state 并将其设置为 integer。 The following is wrong:以下是错误的:

setData(data.push(newFriend));

Instead, please do this:相反,请这样做:

function saveFriend(){
  const newData = [...data, newFriend];
  setData(newData);
}

Or in simple way:或者以简单的方式:

function saveFriend(){
  setData([...data, newFriend]);
}

The reason why this doesn't work is, Array.push() returns the length of the array, thereby, setting the data to a number.这不起作用的原因是Array.push()返回数组的长度,从而将data设置为一个数字。 And an integer doesn't have the map() function so you get the error.而 integer 没有map() function 所以你会得到错误。

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

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