如何在setState中使用数组? [英] How to use an array with setState?

查看:1258
本文介绍了如何在setState中使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下内容将我的数组映射到setState,但是没有设置任何内容,也没有记录任何错误.如果我逐行明确地将其写出,那么它将起作用.关于如何解决这个问题有任何想法或建议吗?

I am currently using the following to map my array to setState but nothing is getting set and no errors are being logged. If I explicitly write it out line by line, it works. Any thoughts or suggestions on how to go about this?

使用数组设置状态:(不设置状态)

const myData = ['message', 'photo', 'isLoggedInhoto'];
const newData = [];

{[...Array(myData.length)].map((x, index) =>
  newData.push(myData[index])
)}

this.setState({
  newData: localStorage.getItem(newData),
})

逐行显示(这可以正常运行setState):

this.setState({
  message: localStorage.getItem('message'),
  photo: localStorage.getItem('photo'),
  isLoggedIn: localStorage.getItem('isLoggedIn')
})

推荐答案

不能将数组用作对象的键和getItem的参数.

You can't use an array as key of an object and as parameter of getItem.

您需要遍历newData并使用

You need to loop through newData and use the computed property name syntax:

newData.forEach(key => this.setState({ [key]: localStorage.getItem(key) }))

或者在重构代码时,您可以通过一个循环和一个setState调用来实现它:

Or in refactoring your code, you can achieve it with a single loop and a single setState call:

const myData = ['message', 'photo', 'isLoggedInhoto']
const newData = {}

{[...Array(myData.length)].map((x, index) =>
  newData[myData[index]] = localStorage.getItem(myData[index])
)}

 this.setState(newData)

这篇关于如何在setState中使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆