Set dynamic key in state via useState React hooks

aks*_*hay 2 reactjs

I want to set dynamic state with dynamic key by uuid in it in functional component Below is example with the class based Component in React

class App extends Component {
  state = {
    [uuid()]: []
  };
Run Code Online (Sandbox Code Playgroud)

How can achieve this with functional component ?

const App = props=>{
 const [list, setList] = useState([uuid()]);
Run Code Online (Sandbox Code Playgroud)

I tried using above approach it gives me output

["4b4c8872-0c35-49a6-a98b-ef7abcb2cef8"]

but desired is ["4b4c8872-0c35-49a6-a98b-ef7abcb2cef8": []]

Thanks in Advance!

Chr*_*Ngo 7

您需要传入一个对象而不是一个数组来 useState

const App = props=>{
 const [list, setList] = useState({ [uuid()] : [] });
Run Code Online (Sandbox Code Playgroud)

如果要向状态值添加新键,则可以执行以下操作。

addList = (e) => {
    setList({
      ...list,  //take existing key-value pairs and use them in our new state,
      [uuid()]: []   //define new key-value pair with new uuid and [].
    })
}
Run Code Online (Sandbox Code Playgroud)