【发布时间】:2019-06-27 18:41:18
【问题描述】:
==已编辑问题,因为不幸的是解决方案不起作用!==
==我现在意识到这是因为我的 Redux Store 没有正确更新!==
我正在尝试使用 Redux 在 ReactJS 中构建一个项目,该项目有一个 Redux 存储,并通过 Axios 获取定期更新状态。
此 Axios fetch 更新初始存储状态正常。
我将商店状态作为道具传递给父级的子元素。
当 store 状态改变时,如果 Child 受到影响,我需要 props 向下传递并重新渲染 Child。
我曾想过,如果我将道具(由 mapStateToProps 设置)发送给 Child,并且状态发生了变化,这会重新发送道具并导致重新渲染,但事实并非如此。
任何有关实现我正在尝试的正确方法的建议将不胜感激。
我已经通过控制台记录了来自 Parent 元素的 componentDidMount 方法的道具,并且我看到了道具更新,正如我所期望的那样;每次我手动更改获取的 JSON 时,都会更改道具以反映这一点。
父元素:
class Parent extends React.Component {
componentDidMount() {
this.props.updatePanels();
console.log(this.props);
this.interval = setInterval(() => {
this.props.updatePanels();
}, 5000);
}
componentWillUnmount() {
clearInterval(this.interval)
}
renderList() {
return this.props.panels.map((panel) => {
return (
<Child key={panel.id} lat={panel.lat} lng={panel.lng} />
);
});
}
render() {
return (
<div>
{this.renderList()}
</div>
);
}
}
子元素:
const Child = props => (
<div key={props.id}>
<div>{props.lat}</div>
<div>{props.lng}</div>
</div>
)
Redux Action Creator
import panelFetch from '../dataCalls/panelFetch';
export const updatePanels = () => {
return async (dispatch) => {
const response = await panelFetch.get("/panelList.json");
console.log(response.data);
dispatch ({
type: 'UPDATE_PANELS',
payload: response.data
});
};
};
Redux 更新面板缩减器
export default (state = [], action) => {
switch (action.type) {
case 'UPDATE_PANELS':
return action.payload;
default:
return state;
}
};
Redux 减速器
import { combineReducers } from 'redux';
import updatePanelsReducer from './updatePanelsReducer'; //compartmentalise our reducer
const panelReducer = () => {
return [{
"id": 400016,
"lat": 51.509865,
"lng": -0.118092
}, {
"id": 400017,
"lat": 51.509865,
"lng": -0.118092
}, {
"id": 400018,
"lat": 51.509865,
"lng": -0.118092
}, {
"id": 400019,
"lat": 51.509865,
"lng": -0.118092
}
];
};
export default combineReducers({
panels: panelReducer,
updatePanels: updatePanelsReducer
});
【问题讨论】: