首页 > 解决方案 > React/Redux - 尽管 Redux 状态发生变化,组件仍未更新

问题描述

我正在尝试更新我的应用程序中的地图组件。我从 redux 收到位置详细信息,我可以在 Redux 开发工具甚至我的浏览器控制台上看到状态变化,但地图组件似乎没有更新,除非我转到另一条路线然后返回包含该组件的路线。

我读过关于 Redux 需要状态是不可变的,并且我已经尝试了所有建议的选项来尝试保持我的状态不可变,但我仍然没有成功。

位置减速器

const initialState = {
  gps: [],
};

export default function locationsReducer(state = initialState, action) {
  switch(action.type) {
    
    case FETCH_LOCATIONS:
      return {
        ...state,
        gps: action.locations,
      };

    default:
      return state;
  }
}

地图结果组件

class MapResults extends Component {
  static defaultProps = {
    center: {
      lat: 0.0236,
      lng: 37.9062
    },
    zoom: 6.5
  };
  render() {
    return (
      <div style={{ height: '70vh', width: '100%' }}>
        <GoogleMapReact
          bootstrapURLKeys={ key: process.env.GOOGLE_MAPS_KEY }}
          defaultCenter={this.props.center}
          defaultZoom={this.props.zoom}
        >
        {this.props.coordinates.gps.map((location, index) => {
          return(
            <Tooltip 
              lat={location.latitude}
              lng={location.longitude}
              title={location.address_name}
              key={index}>
              <Avatar src="/images/gps.svg" />
            </Tooltip>
          )
        })}
        </GoogleMapReact>
      </div>
    )
  }
}

const mapStateToProps = state => {
  return { coordinates: state.locations };
};

export default connect(mapStateToProps)(MapResults);

fetchLocation 方法被正确触发并且坐标被获取并且可以在开发工具中查看。我只需要导航到另一条路线,然后返回地图路线,以便在地图上更新标记。

我希望地图组件在更新位置状态后立即更新 redux 状态更改。

任何帮助都感激不尽。谢谢!

编辑

我正在组合我的减速器的索引减速器

根减速器

import { combineReducers } from "redux";
import individual from "./individualReducer";
import locations from "./locationsReducer";

export default combineReducers({
  individual,
  locations
});

Redux 开发工具清楚地显示状态已更新,正如您 在 redux 状态更新后在图像 Map中看到的那样reduxdevtools 截图

导航到另一条路线并返回地图路线后,您看不到任何标记 地图立即映射 redux 状态更新

您可以看到标记已更新 在我导航到另一条路线并返回地图路线后进行地图

标签: javascriptreactjsreduxreact-redux

解决方案


在您的 Location reducer 中,状态名称为gps,因此应将状态名称映射到组件中。因为状态gps已更新。请更改州名如下

const mapStateToProps = state => {
  return { coordinates: state.gps };
};

推荐阅读