简体   繁体   English

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

[英]Map an array of string to component states in React-Native/ES6

I have a component like this: 我有一个像这样的组件:

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

........
}

And the string is like aaa-bbb-ccc-dd 字符串就像aaa-bbb-ccc-dd

How can I split them and add to the component state. 如何拆分它们并添加到组件状态。 My goal is something like: 我的目标是这样的:

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

Create a new object using reduce and then use this.setState() to finally set the state in just one simple movement. 使用reduce创建一个新对象,然后使用this.setState()最终只需一次简单的移动就可以设置state

Also notice that it is more performant to set the state just once and use the function provided by react. 还要注意,只设置一次状态并使用react提供的功能会更有性能。 Setting the state directly like state[bar] = foo is a bad practice as the documentation says 文档所述,像state[bar] = foo这样直接设置状态是一种不好的做法

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

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

this.setState(newState)

Try 尝试

 let s = "aaa-bbb-ccc-dd"; let state = {} s.split('-').forEach((x,i)=> state[`str${i+1}`]=x ) console.log(state); // and set state using this.setState(state) 

Something like the following should work: 类似于以下内容的东西应该起作用:

const str = "aaa-bbb-ccc-dd"; 
const arr = srt.split("-");   
this.setState({str1 : arr[0],str2 : arr[1], str3: arr[2], str4 : arr[3]});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM