使用useState React hooks在state中设置动态键

11
我想在函数组件中使用uuid来设置具有动态键的动态状态。 下面是React中基于类的组件的示例。
class App extends Component {
  state = {
    [uuid()]: []
  };

如何使用函数式组件实现此功能?

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

我尝试使用上述方法,它给了我输出:

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

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

提前致谢!


我相信你正在寻找一个对象。在JavaScript中,["4b4c8872-0c35-49a6-a98b-ef7abcb2cef8": []]不是可执行的语法。 - Chris Ngo
1个回答

18

你需要传递一个对象而不是数组给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 [].
    })
}

1
@akshay 太棒了!很高兴它对你有用,如果你有任何问题,请告诉我。 :) - Chris Ngo
我该如何在其中添加更多的状态键,例如addList = e => { this.setState({ [uuid()]: [] }); }; - akshay
@akshay,您可以使用与 useState() 一同提供的 setList 方法。在该方法中,我们只需扩展现有状态,然后将新列表作为键添加即可。请参阅我的更新解决方案 :) - Chris Ngo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接