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

时间:2019-03-05 08:24:18

标签: 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]})

但是数组是动态列表,我应该在数组和setState中映射它的每个项目都在一个setState中 我尝试

 object.setState(
        {...stateName:accountCodes}
      )

但不起作用,我也尝试以下操作,不会抛出语法错误:

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

我该怎么办?

3 个答案:

答案 0 :(得分:2)

您可以使用reduce函数来实现它。数组中的每次迭代都会将元素添加到具有计算属性的对象中:

cmd+shift+e

工作示例:

const accountcode = { a: 1, b: 2 };
const array = ["first","second","third"];
this.setState(array.reduce((acc, val) => ({[val]: accountcode, ...acc}), {}));
class App extends React.Component {
    componentDidMount(){
        const accountcode = { a: 1, b: 2 };
        const array = ["first", "second", "third"];
        this.setState(array.reduce((acc, val) => ({ [val]: accountcode, ...acc }), {}));
    }

    render(){
        console.log(this.state)
        return <div></div>
    }
}

ReactDOM.render(<App/>, document.getElementById('root'))

答案 1 :(得分:1)

您正在考虑从数组创建对象。问题只是creating an object from an array的改写。

对于您而言,解决方案可能如下:

Gradle

答案 2 :(得分:0)

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

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的每个属性使用相同的Object。您可以写newState[el] = JSON.parse(JSON.stringify(accountCode));来防止这种情况!