Dispatch Action,React + Redux

时间:2019-02-15 13:08:02

标签: javascript reactjs redux

所以我正在执行一个API GET请求并在reducer上设置数据,但是该组件呈现两次,第一次在分派之前,然后在第二次,第一次导致地图功能问题

该如何避免两次渲染并解决地图功能问题?

App.js

componentDidMount(){
      this.props.carregarLojas();
    }

render(){
   const { lojasTeste } = this.props;
   //rendering 2 times
   console.log(lojasTeste);

   return(
    <div>
        lojasTeste.map((i, index) => (
        <h1>{i.name}</h1>
        ))
    </div>
   )

}

const mapStateToProps = store => ({
    lojasTeste: store.lojaState.lojasTeste
});

const mapDispatchToProps = dispatch => {
    return {
        carregarLojas: () => {
        dispatch(carregarLojas());
      }
    };
  };

export default connect(mapStateToProps, mapDispatchToProps)(App);

Action.js

export const setarLojas = (lojas) =>{
    return {
      type: SETAR_LOJAS,
      data: lojas
    }
  }

  export const carregarLojas = () => {
    return (dispatch) => {
      return API.get('loja')
      .then(response => {
        dispatch(setarLojas(response.data))
      })
      .catch(error => {
        throw(error);
      })
    }

Reducer.js

const initialState ={
    lojasTeste: {}
}

export const lojaReducer = (state = initialState, action) => {
   switch (action.type){
     case SETAR_LOJAS:
      return {
      ...state,
      lojasTeste: action.data 
      }
     default:
       return state;
   }
}

1 个答案:

答案 0 :(得分:0)

双重渲染是完全正常的: 您的组件仅渲染一次,然后调用异步的carregarLojas方法。解决后,该方法将更新您的redux存储,该存储与组件的props(mapStateToProps)连接。更新道具后,它会自动重新渲染。

此外,对于您的地图问题,您没有将lojasTeste初始化为数组,而是将其初始化为对象。您不能在对象上使用地图(参见https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map