【发布时间】:2019-01-19 03:29:47
【问题描述】:
我在一个数据库中有两个示例,其结构如下:
state:
interaction: [
{creatorId: 123,
title: exampleTitle1
},
{creatorId: 1234,
title: exampleTitle2}
]
这家店是这样的:
const store = createStore(
combineReducers({
...(other reducers)
interaction: interactionReducer
}),
applyMiddleware(thunk)
);
我根据componentDidMount 从 API 获取基础:
componentDidMount() {
this.props.dispatch(fetchBases());
}
有了这个动作创建者:
export const BASE_SUCCESS = "BASE_SUCCESS";
export const baseSuccess = bases => ({
type: BASE_SUCCESS,
bases,
});
和操作(当我控制台日志action 数组返回就好了):
export const fetchBases = () => dispatch => {
fetch(`${API_BASE_URL}/base/list`, {
method: "GET",
})
.then(res => {
if (!res.ok) {
return Promise.reject(res.statusText);
}
return res.json();
})
.then(bases => dispatch(baseSuccess(bases)))
.catch(error => {
console.log("GET request failed", error);
});
};
减速器:
export default function interactionReducer(state = initialState, action) {
if (action.type === BASE_SUCCESS) {
return Object.assign({}, state, {
bases: action.bases,
});
}
return state;
}
在组件中,我有以下内容:
const mapStateToProps = state => ({
bases: state.bases,
});
export default requiresLogin()(connect(mapStateToProps)(DashContent));
当我在组件中控制台日志this.state 时,我得到null 的日志。我无法弄清楚为什么它没有正确填充数据以挽救我的生命。之前它只显示了数组中的一项,但现在它为空
【问题讨论】:
-
this.state?您的组件中是否有任何本地状态。你检查过:this.props.bases? -
另外,它应该是
bases: state.interaction.bases,因为您的全局状态中有一个interaction状态。