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
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.
Also notice that it is more performant to set the state just once and use the function provided by react. Setting the state directly like state[bar] = foo
is a bad practice as the 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)
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]});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.