通过useState React挂钩将动态密钥设置为状态

时间:2019-06-03 07:59:38

标签: reactjs

我想通过功能组件中的uuid通过动态键设置动态状态 以下是React中基于类的Component的示例

class App extends Component {
  state = {
    [uuid()]: []
  };

如何通过功能组件实现这一目标?

const App = props=>{
 const [list, setList] = useState([uuid()]);

我尝试使用上述方法给我输出

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

但需要的是 ["4b4c8872-0c35-49a6-a98b-ef7abcb2cef8": []]

预先感谢!

1 个答案:

答案 0 :(得分:4)

您需要将对象而不是数组传递给useState

const App = props=>{
 const [list, setList] = useState({ [uuid()] : [] });

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

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 [].
    })
}
相关问题