首页 > 解决方案 > Dispatch Action,React + Redux后无法使用地图功能

问题描述

所以我正在做一个API GET请求并在reducer上设置数据,但是组件渲染了两次,第一次在调度之前,另一个在之后,第一个导致地图功能问题

我该怎么做才能避免渲染两次并解决地图功能问题?

应用程序.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);

动作.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);
      })
    }

减速器.js

const initialState ={
    lojasTeste: {}
}

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

标签: javascriptreactjsredux

解决方案


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

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


推荐阅读