简体   繁体   中英

React - How to use hook useState props to create a map function

I am trying to use props to create a map, but it shows this error:

TypeError: data.map is not a function

Here is the code of the main page:

const Portfolio = () => {
  
  const [portfolio_assets, setPortfolioAssets] = useState([]);
  const auth = useContext(AuthContext);
  const onFetchPortfolioAssets = useCallback(async () => {
      const json = await fetchPortfolioAssets(auth.token);
      if (json) {
          setPortfolioAssets(json);
      }
      }, [auth.token]);
      useEffect(() => {
      onFetchPortfolioAssets();
      }, [onFetchPortfolioAssets]);

  return (
    <MainLayout>
       <Dashboard data={portfolio_assets} />
    </MainLayout>
  )
};

export default Portfolio;

this is the page with Dashboard:

const Dashboard = (data=[]) => {
    console.log(data)
    
    return (
        <Row>
            <table className='table table-striped'>
                <tr>
                    <th>Category</th>
                </tr>
                {data.map((portfolio_asset) => (
                <tr key={portfolio_asset.id} lg={12}>
                    <td>{portfolio_asset.category}</td>                    
                </tr>
                ))}
            </table>
        </Row>
  )
};

export default Dashboard;

Here is the console.log, so the object is there, but i didn`t understand how to use.map

{data: Array(0)}data: [][[Prototype]]: Object

{
    "data": [
        {
            "id": 1,
            "category": "Category 1",
        },
        {
            "id": 2,
            "category": "Category 2",
        },
        {
            "id": 3,
            "category": "Category 2",
        },
    ]
}

You made a mistake by getting data object in Dashboard. The parameter you get contains all the props, not only data, so you have to replace it by:

const Dashboard = ({data=[]}) => {

with {} around data to get data from the props object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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