还原相当新,并且已通过官方指南。现在我想尝试做一些独奏。我有两个减速器,我正在使用react-thunk。当我在第一个之后发出动作时,它会清除我的另一个减速器的集合。为了说明我的意思,我有:
Actions.js
import axios from 'axios';
function fetchAtms() {
return axios.get('http://localhost:4567');
}
export const recievedAtms = (atms) => {
return {
type: 'RECIEVED_ATMS',
atms
}
}
export const completed = () => {
return {
type: 'COMPLETED',
}
}
export const loadMore = () => {
return {
type: 'LOAD_MORE',
}
}
export const loadAtms = (forPerson) => {
return function (dispatch) {
return fetchAtms().then((response) => {
let atms = response.data.map((item) => {return item['location']})
dispatch(recievedAtms(atms));
// When dispatch(completed()); is called
// it is clears my app collection.
dispatch(completed());
// $r.store.getState() => Object {app: {atms: []}, isLoading: false, router: Object}
}, (error) => {
console.log('implement me');
})
}
}
减速
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
const app = (state = {}, action) => {
switch (action.type) {
case 'RECIEVED_ATMS':
return {
atms: action.atms
}
default:
return {};
}
}
const isLoading = (state = true, action) => {
switch (action.type) {
case 'COMPLETED':
return !state;
default:
return state;
}
}
const appReducer = combineReducers({
app,
isLoading,
router: routerReducer
});
export default appReducer;
Store.js
import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware} from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import thunk from 'redux-thunk';
import appReducer from './reducers/app';
export const history = createHistory()
const middleware = routerMiddleware(history);
const store = createStore(appReducer, applyMiddleware(middleware, thunk));
export default store;
如果您在Actions.js
功能I {
loadAtms
中磨练
当我发送completed()
时,它会清除我的atms集合。我不完全确定。我不希望因为两个减速器之间的状态是分开的。我的期望是:
在我解雇completed()
之后,我不希望它清除我的自动收集。调用completed()
后生成的状态应如下所示:
{
isLoading: false,
app: {atms: [{id: 1}, {id: 2}, {id: 3}]}
}
目前正在发生的事情是:
{isLoading: false, app: {}}
对我在这里做错了什么的任何想法。
答案 0 :(得分:1)
如果动作不是它正在寻找的动作,你的atms reducer将返回{}
。相反,你应该回归state
我相信。所以:
const app = (state = {}, action) => {
switch (action.type) {
case 'RECIEVED_ATMS':
return {
atms: action.atms
}
default:
return state;
}
}