Question about adding react native picker.item.

Asked 2 years ago, Updated 2 years ago, 114 views

I want to take the db value from the server and add it to the react native picker.

import React, {Component} from 'react';
import {View, Picker} from 'react-native';
import axios from 'axios'

class INPUT extends Component{
    constructor(props){
        super(props)
        this.arr = []
        axios.get('http://beam1100.cafe24app.com/input').then((res)=>{
            for(var i in res.data.results){
                var results = res.data.results
                this.arr.push(<Picker.Item key={results[i].num} value={results[i].name} label={results[i].name}/>)
            }
        })
    }

    render(){
        return(
            <View>
                <Picker>
                    {this.arr}
                </Picker>
            </View>
        )
    }
}

export default INPUT

The imported db arrays are as follows:

Array [

Object { "name": "bench press", "num": 1, },

Object { "name": "Squat", "num": 2, },

Object { "name": "deadlift", "num": 3, },

]

No errors are displayed and no additions are made. Why is this happening?

react-native

2022-09-21 10:22

1 Answers


class INPUT extends Component{

    constructor(props){
        super(props)

        this.state={
            arr:[],
            selected:null
        }

        axios.get('http://beam1100.cafe24app.com/input')
        .then((res)=>{
            var results = res.data.results
            for(var i in results){
                var picker = < Picker.Item key={results[i].num} value={results[i].name} label={results[i].name}/>
                this.setState({arr:this.state.arr.concat(picker)});
            }
        })
    }

    render(){
        return(
            <View>
                <Picker
                    selectedValue={this.state.selected}
                    onValueChange={(e)=>{
                        this.setState({selected:e})
                    }}
                >
                    {this.state.arr}
                </Picker>
            </View>
        )
    }
}

I modified it using the state

According to the reaction cycle, the render runs after the construction is finished, but why this.I don't know if the empty array is transferred from the constructor to the render using the variable. Does anyone know?


2022-09-21 10:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.