我在数据库中有两个示例,其结构如下:
state:
interaction: [
{creatorId: 123,
title: exampleTitle1
},
{creatorId: 1234,
title: exampleTitle2}
]
商店是这样的:
const store = createStore(
combineReducers({
...(other reducers)
interaction: interactionReducer
}),
applyMiddleware(thunk)
);
我从 API 获取基础componentDidMount
:
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
. 我无法弄清楚为什么它没有正确填充数据以挽救我的生命。早些时候它只显示了数组中的一项,但现在它为空