【发布时间】:2019-04-20 21:27:33
【问题描述】:
我正在尝试通过每次更新商店时从redux store 获取数据来更新我的home componentstate。我不确定下面的代码有什么问题。我无法收听我的 `home 组件中的存储更改。
我的调度函数在这个类中处理。
export class GanttFilter extends Component {
...
handleSubmit = () => {
this.gFilter.filterGanttData(this.formValues)
.then((result) => {
if (result.data)
this.props.dispatch(ganttActions.loadGanttData(result.data));
});
}
...
GanttFilter.propTypes = {
dispatch: PropTypes.func.IsRequired
};
function mapStateToProps(state) {
return {
ganttData: state.gantt.ganttData
};
}
export default connect(mapStateToProps)(GanttFilter);
每次调用 dispatch 并且数据发生变化时,我想做的是更新我的home component 中的状态。这是组件。
export class Home extends Component {
constructor() {
super();
this.state = {
data: [],
links: []
};
}
render() {
return (
<div className="fill">
<Gantt data={this.state.data} links={this.state.links} />
</div>
);
}
}
Home.propTypes = {
data: PropTypes.IsRequired
};
function mapStateToProps(state) {
return {
data: state.gantt.ganttData
};
}
export default connect(mapStateToProps)(Home);
当我设置断点时,函数mapStateToProps 永远不会被命中。如何从 home 组件监听 store 的变化并更新状态?
编辑:这是包装组件
function renderApp() {
// This code starts up the React app when it runs in a browser. It sets up the routing
// configuration and injects the app into a DOM element.
const baseUrl = document.getElementsByTagName("base")[0].getAttribute("href");
ReactDOM.render(
<ReduxProvider store={store}>
<AppContainer>
<BrowserRouter children={routes} basename={baseUrl} />
</AppContainer>
</ReduxProvider>,
document.getElementById("react-app")
);
}
减速器
const actionTypes = require('../actions/actionTypes');
const gantt = {
ganttData: [],
selectedTask: null
};
export default function ganttReducer(state = gantt, action) {
switch (action.type) {
case actionTypes.loadGanttData:
return { ...state, ganttData: [...action.ganttData] };
default:
return state;
}
}
根减速器
import { combineReducers } from 'redux';
import gantt from './ganttReducer';
const rootReducer = combineReducers({
gantt
});
export default rootReducer;
动作
const actionTypes = require('./actionTypes');
export function loadGanttData(ganttData) {
return { type: actionTypes.loadGanttData, ganttData };
}
export function getSelectedTask(ganttTask) {
return { type: actionTypes.setSelectedTask, ganttTask };
}
【问题讨论】:
-
你能展示一下你的减速器是什么样子的吗?
-
问题中没有足够的细节来提供答案。
result.data是什么?props.dispatch是什么?你在哪个mapStateToProps设置断点?您是否在控制台中看到任何错误? -
@DanO
result.data是一个对象数组。我都断点了,home component下的那个没有达到断点,gantt filter工作正常。 -
@OrthoHomeDefense 你确定
GanttFilter中的result.data不为空吗? -
@nebuler 他们不是空的。我只能收听
GanttFIlter中的存储更改,但不能在Home中收听我的connect函数在Home组件中是否有问题?
标签: javascript reactjs redux