Handling undefined/null properties in components during first render

后端 未结 3 856
春和景丽
春和景丽 2021-01-13 01:28

I\'m learning react and it\'s great, but i\'ve ran into an issue and i\'m not sure what the best practice is to solve it.

I\'m fetching data from an API in my compon

3条回答
  •  难免孤独
    2021-01-13 01:52

    I set initial state in constructor. You can of course set initial state of component as static value - empty array or object. I think better way is to set it using props. Therefore you can use you component like so or (which takes value of items from defaultProps object because you not pass it as prop).

    Example:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    
        class App extends Component {
            constructor(props) {
                super(props);
                this.state = {
                    items: [], // or items: {...props.items} 
                };
    
    
    
            }
            async componentDidMount() {
                const res = await this.props.getItems();
                this.setState({items: res.data.items})
            }
            render() {
                   return 
    } }; App.defaultProps = { items: [] }

提交回复
热议问题