gpt4 book ai didi

javascript - 将字符串数组映射到 React-Native/ES6 中的组件状态

转载 作者:行者123 更新时间:2023-11-30 09:17:14 25 4
gpt4 key购买 nike

我有这样一个组件:

export default class Demo extends Component{
constructor(props){
super(props)
this.state = {
str1: '',
str2: '',
str3: '',
str4: '',
}
}

........
}

字符串就像aaa-bbb-ccc-dd

如何拆分它们并添加到组件状态。我的目标是这样的:

str1: 'aaa',
str2: 'bbb',
str3: 'ccc',
str4: 'dd'

最佳答案

使用 reduce 创建一个新对象然后使用 this.setState() 通过一个简单的 Action 最终设置 state

另请注意,仅设置一次状态并使用 React 提供的功能会提高性能。像 state[bar] = foo 这样直接设置状态是一种不好的做法,因为 documentation says

let string = "aaa-bbb-ccc-dd";

const newState = string.split('-').reduce((a, c, i) => {
a[`str${i+1}`] = c;
return a;
}, {})

this.setState(newState)

关于javascript - 将字符串数组映射到 React-Native/ES6 中的组件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com