Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何设置状态列表的所有元素_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 如何设置状态列表的所有元素

Javascript 如何设置状态列表的所有元素,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个字符串名数组,我想做下面的事情 let accountcode:{a:1,b:2}; let array=["first","second",third]; this.setState({[array[0]:accountCode,array[1]:accountCode,array[3]:accountCode]}) 但数组是动态列表,我应该在数组中映射并在一个集合状态中设置它的每一项 我试着 但不起作用,我也尝试了以下方法,但没有抛出语法错误: object.

我有一个字符串名数组,我想做下面的事情

  let accountcode:{a:1,b:2};
    let array=["first","second",third];
    this.setState({[array[0]:accountCode,array[1]:accountCode,array[3]:accountCode]})
但数组是动态列表,我应该在数组中映射并在一个集合状态中设置它的每一项 我试着

但不起作用,我也尝试了以下方法,但没有抛出语法错误:

 object.setState(
        stateName.map(s=>{[s]=accountCodes})
      )

我该怎么办?

您正在考虑从数组创建对象。这个问题只是对这个问题的重新表述

在您的情况下,解决方案可能如下所示:

let accountCode = {a: 1, b: 2};
let array = [1, 2, 3, 4];

let output = {};
for (let key of array) {
    output[key] = accountCode;
}

// Almost forgot this
this.setState(output);
您可以使用该函数来实现它。数组中的每次迭代都将使用计算属性将元素添加到对象中:

const accountcode = { a: 1, b: 2 };
const array = ["first","second","third"];
this.setState(array.reduce((acc, val) => ({[val]: accountcode, ...acc}), {}));
工作示例:

类应用程序扩展了React.Component{
componentDidMount(){
常量accountcode={a:1,b:2};
常量数组=[“第一”、“第二”、“第三”];
this.setState(array.reduce((acc,val)=>({[val]:accountcode,…acc}),{});
}
render(){
console.log(this.state)
返回
}
}
ReactDOM.render(,document.getElementById('root'))

您可以简单地编写如下内容:

let accountCode = {a:1, b:2};
let array = ["first", "second", "third"];

/* Function in which you will call setState */
let newState = {};
array.forEach(el => {
  newState[el] = accountCode;
});
不过,我建议您不要简单地编写
newState[el]=accountCode
否则,您将对
newState
的每个属性使用相同的对象。您可以编写
newState[el]=JSON.parse(JSON.stringify(accountCode))以防止出现这种情况

let accountCode = {a:1, b:2};
let array = ["first", "second", "third"];

/* Function in which you will call setState */
let newState = {};
array.forEach(el => {
  newState[el] = accountCode;
});