简体   繁体   中英

How to use useState with an object?

How to use useState with an object? This is not the same as other similar questions. My code below gives strange error...

import React, { useState } from "react";

export default function App() {
    const [data, setData] = useState({data: 'something'});

    return (
         <h1>Data: {data}</h1>
    );
}

https://codesandbox.io/s/usestate-with-an-object-m176t?file=/src/App.js:0-167

Your problem is not at the useState .
Your problem happens when you try to render the {data} , because is an object. You need to render a property.

In this case, your data object is:

{
  data: 'something'
}

To render the value, you should:

import React, { useState } from "react";

export default function App() {
    const [data, setData] = useState({data: 'something'});

    return (
         <h1>Data: {data.data}</h1>
    );
}

You can not pass objects as children in React .

Please note that you are passing an object <h1>Data: {data}</h1> , the data is an object that has a data property

Solution

import React, { useState } from "react";

export default function App() {
    const [data, setData] = useState({data: 'something'});

    return (
         <h1>Data: {data.data}</h1>
    );
}

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