Home > OS >  put each element of an array in state and then show it to render ()
put each element of an array in state and then show it to render ()

Time:09-02

How do I put an array in a state and how do I show the result in render ()?

export default class UserList extends Component {
constructor(props){
    super(props); 
        this.state={  
          post:[
            {id:"0", author:"", delay:"", status:""},
            {id:"1", author:"", delay:"", status:""},
            {id:"2", author:"", delay:"", status:""}
 ]
}
putintostate(){
var author_array= ["Mark","Jess","Alice"]
var delay_array= ["12","13","14"]
var status_array= ["1","2","3"]
this.setState.post.map(new_dato=>this.setState.post.author(new_dato))
this.setState.post.map(new_dato=>this.setState.post.delay_array(new_dato))
this.setState.post.map(new_dato=>this.setState.post.status_array(new_dato))
}
 componentDidMount() {
    this.putintostate()  
  }
render(){
return(
<text>{this.state.post.author}<Text>
<text>{this.state.post.delay}<Text>
<text>{this.state.post.status}<Text>

)}

i want to put the first element of the author_array array in the state post with id = 1 in the cmapo auhtor. I want as output:

            id:"0", author:"Mark", delay:"12", status:"1"
            id:"1", author:"Jess", delay:"13", status:"2"
            id:"2", author:"Alice", delay:"14", status:"3"

CodePudding user response:

I will not implement any guards for the following. I expect that all three arrays contain the same number of elements. You could then implement it as follows.

const author_array = ["Mark", "Jess", "Alice"]
const delay_array = ["12", "13", "14"]
const status_array = ["1", "2", "3"]
const result = author_array.map((item, index) =>
  ({
    id: index.toString(),
    author: item,
    delay: delay_array[index],
    status: status_array[index]
  }));

Then, set the new state.

this.setState({post: result});

Then, map over the state in the render function and render whatever you want. I will use a text component in my example.

render(){
    return(
       <View>
        {
            this.state.post.map(item => {
               return <>
                <Text>{this.state.post.author}</Text>
                <Text>{this.state.post.delay}</Text>
                <Text>{this.state.post.status}</Text>
               </>
            })
        }
       </View>
)}

Here is a little snack.

  • Related