[英]Create objects with map function, currentValue as a object key
In my ReactApp, I keep in state list of users (fetched from backend API).在我的 ReactApp 中,我保留了用户的状态列表(从后端 API 获取)。 It is called "currentUsers".
它被称为“currentUsers”。
class Lobby extends React.Component {
constructor(props) {
super(props);
this.state = {
currentUsers: ["TestUser1", "TestUser2"],
buttonList: [],
}
}
I would like to populate buttonList to have array of object where array will look like this(example):我想填充 buttonList 以拥有对象数组,其中数组将如下所示(示例):
[{
"TestUser1": {
"inviteButtonValue": "Invite",
"chatButtonValue": "Chat"
}
},
{"TestUser2": {
"inviteButtonValue": "Invite",
"chatButtonValue": "Chat"
}
}]
There is my main function.有我的主要功能。
produceButtonValues = (currentUsersList) => {
let inputList = currentUsersList
.map( (nickname) => {
return {
nickname: {
"inviteButtonValue": "Invite",
"chatButtonValue": "Chat"
}
};
}
);
this.setState({buttonList: inputList});
}
I tried to use map but it looks like I cannot get array element as object key, ie "TestUser1" etc. but got "nickname" instead (seen in "Components" tab in Firefox DevTools Add-on)我尝试使用地图,但看起来我无法将数组元素作为对象键,即“TestUser1”等,但得到了“昵称”(在 Firefox DevTools Add-on 的“组件”选项卡中看到)
...
{nickname: {
"inviteButtonValue": "Invite",
"chatButtonValue": "Chat"
}
}
...
I trigger my function as below:我触发我的功能如下:
componentDidMount() {
this.produceButtonValues(this.state.currentUsers);
How to solve it?如何解决? By the way: when I run
console.log(this.state.buttonList);
顺便说一句:当我运行
console.log(this.state.buttonList);
just after setState
, I still see empty array as it was made in initial state.就在
setState
之后,我仍然看到空数组,因为它是在初始状态下创建的。 Why?为什么?
It's called Property accessors
它被称为
Property accessors
You use it like this:你像这样使用它:
currentUsersList.map(nickname => ({
[nickname]: {
inviteButtonValue: Invite,
chatButtonValue: Chat
}
});
You are looking for this:你正在寻找这个:
produceButtonValues = (currentUsersList) => {
let inputList = currentUsersList
.map( (nickname) => {
return {
[nickname]: {
"inviteButtonValue": "Invite",
"chatButtonValue": "Chat"
}
};
}
);
this.setState({buttonList: inputList});
}
To use a variable as the value of an object key you need to wrap it with []
要将变量用作对象键的值,您需要用
[]
包裹它
You could make use of a string as key instead of a variable-name-key.您可以使用字符串作为键而不是变量名键。 In this case you can use a template-string to enforce the key for beeing a string
在这种情况下,您可以使用模板字符串来强制执行字符串的键
For Example:例如:
produceButtonValues = (currentUsersList) => {
let inputList = currentUsersList.map( nickname => {
return {
`${nickname}`: {
"inviteButtonValue": "Invite",
"chatButtonValue": "Chat"
}
};
});
this.setState({buttonList: inputList});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.