【发布时间】:2020-01-03 21:53:11
【问题描述】:
我有一个问题,当我从 API 获取数据并更新存储时,数据没有改变。它被绑定为道具,我认为它应该改变,我注意到的另一件事是它在商店更新后不会调用 mapStateToProps 。当我给商店一些初始值时,它会显示它,所以我认为它可以看到商店,其他东西显然是错误的,但我不知道是什么。
减速器代码:
import { ADD_POST } from "../actions/addAction";
import { GET_POSTS } from "../actions/getAction";
import { DELETE_POST } from "../actions/deleteAction";
import { UPDATE_POST } from "../actions/updateAction";
import axios from "axios";
const initialState = {
posts: []
};
export default function postsReducer(state = initialState, { type, payload }) {
switch (type) {
case ADD_POST:
state = state.slice();
state.push(payload);
break;
case GET_POSTS:
axios
.get("http://localhost:59511/api/post?date=31-12-2019")
.then(response => {
response.data.forEach(thePost => {
state.posts = [...state.posts, thePost];
});
console.log(state.posts);
return state;
});
break;
default:
return state;
}
return state;
}
索引(这里我创建了我的商店并用提供者包装了应用程序组件):
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { combineReducers, createStore } from "redux";
import { Provider } from "react-redux";
import postReducer from "./reducers/postsReducers";
const allReducers = combineReducers(
{
post: postReducer
},
window.devToolsExtension && window.devToolsExtension()
);
const store = createStore(allReducers);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
像这样在我的组件中映射它:
const mapStateToProps = state => ({
posts: state.post.posts
});
如果你们需要其他任何东西,请告诉我,我有一个文件有点大,所以如果没有必要我不想添加它,我现在正在用头撞墙几个小时.提前致谢
===编辑=== 我还将我的动作映射到道具
const mapActionToProps = {
onDeletePost: deletePost,
onUpdatePost: updatePost,
onGetPost: getPosts
};
我的动作定义为
export const ADD_POST = "posts:addPost";
export function addPost(newTitle, newHours, newDate) {
return {
type: ADD_POST,
payload: {
id: new Date().toString(),
title: newTitle,
hours: newHours,
date: new Date().toLocaleDateString()
}
};
}
所以我已经在那里定义了动作,所以我不确定我是否需要 dispatchToAction?在我们说话的时候,我正在查找它,并会尝试做点什么,只是有点困惑。 ==编辑结束==
【问题讨论】:
标签: reactjs redux frontend state