我有一个字符串名称数组,我想在下面做
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})
)
我该怎么办?
最佳答案
您可以使用 reduce功能来实现它。数组中的每次迭代都会将元素添加到具有计算属性的对象中:
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'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>
<div id='root'>
关于javascript - 如何设置状态列表的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54998319/