REACT 渲染前获取

REACT fetch before rendering

我尝试映射获取的数据,但我的映射总是出错,因为在我使用映射函数之前尚未获取数据。我可以使用点击事件从我获取的数据中获取特定元素。

parent class 在我获取数据的地方,我需要啤酒数据进行映射。

class App extends Component{


    constructor(props){
        super(props);
        this.props.fetchUser();
        this.props.fetchBeers();
    }

class 我尝试在其中映射我的啤酒:

class BeersLanding extends Component{



 getBeers = () => {
     let beers= this.props.beers;
     console.log(beers);
     console.log(beers[0]);
     console.log(beers[1]);

 }

 constructor(props){
     super(props);

 }

render(){

    const {loading} =this.props;


   console.log(this.props.beers)

    return(


        <div style={{textAlign:'center'}}>

           ...

                <input type="text" placeholder="Search.." name="search"></input>
                <button type="submit" onClick={() =>this.getBeers()} >Submit</button>

            <div className={'beersContainer'}>

                 {this.props.beers.map((beer,index) =>(
                    <div className={'card'}>
                    hello
                    </div>
                ))}  

            </div>
        </div>
    );
}

}

操作方法:

export const fetchBeers = () => async dispatch => {

    const res = await axios.get('/api/beers');
    dispatch({type:FETCH_BEERS, payload:res.data});
};

减速器:

export default function(state=null, action){

    // console.log(action);
    switch(action.type){
    case FETCH_BEERS:
        return action.payload; 

    default:
        return state;
    }
}

有两个选项可以解决这个问题,第一个选项,我建议使用它,方法是使用 defaultProps 并将蜜蜂的默认值设置为数组。 第二个选项是在映射数据之前添加条件

{this.props.beers && this.props.beers.map((beer,index) =>(
                    <div className={'card'}>
                    hello
                    </div>
                ))}  

对于此类问题,我建议使用 React 生命周期挂钩。

componentDidMount() {
    this.props.YOURACTIONS()
}

所以这会在加载组件时发生。