javascript - 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
});
解决方案
在您的 Location reducer 中,状态名称为gps
,因此应将状态名称映射到组件中。因为状态gps
已更新。请更改州名如下
const mapStateToProps = state => {
return { coordinates: state.gps };
};
推荐阅读
- javascript - 如何重新打开浏览器以使用其他帐户?
- ocaml - 无法定义一个新变量来保存我的 rlist
- javascript - 如何保护 AJAX 或 javascript Web 应用程序
- python - 具有复杂数据结构的 JSON 响应
- python - 比较多组列表(Python)
- redwoodjs - 如何在 RedwoodJS 上创建字段解析器
- javascript - 悬停时滚动链接文本 - 无尽的选框效果
- flutter - 从 main() 调用 await rootBundle.loadString(...) 时,Flutter 应用程序挂起
- azure-cosmosdb - IdentityServer Access Token 长度短
- html - 除非在角色后面,否则 HR 不会出现