【问题标题】:REACT fetch before rendering渲染前 REACT fetch
【发布时间】:2018-05-23 18:18:04
【问题描述】:

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

我获取数据的父类,我需要啤酒数据进行映射。

class App extends Component{


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

我尝试映射啤酒的课程:

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;
    }
}

【问题讨论】:

  • 您收到有关选择标签的错误
  • 不要在构造函数中触发获取,使用componentDidMount。此外,无论您是否正在加载,您都需要保持状态。然后是在渲染“啤酒”之前简单检查布尔值的问题。

标签: reactjs redux axios redux-thunk


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-13
      • 2018-04-21
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      相关资源
      最近更新 更多