javascript - 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;
}
}
解决方案
双重渲染是完全正常的:您的组件渲染一次,然后调用carregarLojas
异步方法。解决后,该方法将更新您的 redux 存储,该存储与您的组件 (mapStateToProps) 的 props 连接。当一个道具被更新时,它会自动导致重新渲染。
另外,对于您的地图问题,您没有初始化lojasTeste
为数组,而是初始化为对象。您不能在对象上使用地图(参见https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map)
推荐阅读
- javascript - 如何使用 Chromium Embedded Framework 将 JS 注入应用程序
- excel - Excel VBA - 从多张有条件的工作表中复制并放置在不同工作表中的某个单元格中
- django - Django Formset image.url 未填充
- java - EclEmma(Jacocco) 显示未覆盖的行,即使该行已执行
- javascript - WEBPACK 构建脚本无需更改即可中断
- node.js - 当我通过 962122961v 时 findOneAndRemove 删除了错误的用户,它将删除 962122963v
- c++ - 如何存储用户输入到 for 循环中的值?
- google-drive-api - 提交同意屏幕进行验证是否会自动触发未经验证的应用屏幕?
- python - 关于 MTCNN 中的人脸检测,在 align_dataset_mtcnn.py 中。这是什么意思?
- php - 如何将 ReCAPTCHA 集成到 WORDPRESS 中的默认登录表单/评论中