2

The below component of mine is very unstable.
"this.state.list" gets value from this.props. But immediately the state becomes "undefined".
Just not able to figure out why??? What is wrong with this code.

this.state.dropList

["2 mg/dL  -   Feb 21 2021 12:11:00", "5 mg/dL  -  Feb 21 2021 01:11:00"]

<ListItem dropList={this.state.dropList} />.  //call the component


export default class ListItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: []
        }
      }
    

     componentDidMount() {
        const {dropList} = this.props;
       this.setState({list: dropList})
    }


        render(){
            console.log("droplist inside:", this.state.list)
            return (
                <View>
            {
            this.state.list !== "" ?      
                <View>
                {      
                this.state.list.map((l,i) => (
                  <View key={l}>
                    <ListItem   
                    containerStyle={{padding: 4, backgroundColor:'#D3D3D3'}}
                    title={l}
                    accessible={true}
                    />
                    </View>
                ))             
              }
              </View>
              : null
           }
     </View>
            )
        }

}

Log

droplist inside: ["2 mg/dL  -   Feb 21 2021 12:11:00", "5 mg/dL  -  Feb 21 2021 01:11:00"]
droplist inside: undefined
droplist inside: undefined
droplist inside: undefined



grooot
  • 446
  • 2
  • 10
  • 31

1 Answers1

2

It seems you're setting the list property of your state to the reference of dropList. Instead you want to do a copy by value of dropList. Because dropList is an array of primitive types, then you want to do this.setState({list: [...dropList]}) instead of this.setState({list: dropList}). If dropList was another type of collection or structure, you would need to do a deep clone as explained in this answer.

Please try that and let me know if it helps :-)

Rosana Rufer
  • 599
  • 8
  • 15