我使用redux和redux-persist以及redux-thunk。
只有部分州没有坚持。可能是什么原因?它是一种强制坚持当前状态的方法吗?当我调用reducers时,状态会更新。但是当我重新加载应用程序时,状态的某些部分仍然是旧的。 (空)
我认为它从初始状态开始占用状态的某些部分,所以我在初始状态中添加了一些条目,即使这样,它也会返回空对象。没有从initialState获取它们。
提前致谢。
只有讨论学生才能坚持
商店设置:
import React from "react";
import { View, AsyncStorage } from 'react-native';
import { applyMiddleware, createStore, compose } from 'redux';
import { Provider } from 'react-redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { reducer } from './reducers';
import Container from './Container';
const middlewares = [thunk];
const logger = createLogger();
middlewares.push(logger);
const store = createStore(reducer, compose(
applyMiddleware(...middlewares)
), autoRehydrate({ log: true }));
persistStore(store, {storage: AsyncStorage});
const Root = () => (
<Provider store={store}>
<Container />
</Provider>
);
export default Root;
减速机的一部分:
import {REHYDRATE} from 'redux-persist/constants';
export const types = {
SYNCHRONISE_DISCUSSIONS: 'SYNCHRONISE_DISCUSSIONS'
};
export const actionCreators = {
synchroniseDiscussions: (args) => {
return dispatch => {
/// Call API
synchroniseDiscussionsAPI()
.then((res) => {
return dispatch(synchroniseDiscussions(res))
})
.catch((e) => {
console.log(e)
})
}
}
}
const synchroniseDiscussions = (args) => {
return {type: types.SYNCHRONISE_DISCUSSIONS, payload: args}
}
const initialState = {
rehydrated: false,
discussionStudents: [],
discussionGroups: [],
discussionsMessages: [],
discussionParticipants: []
}
export const reducer = (state = initialState, action) => {
const {
discussionStudents,
discussionGroups,
discussionsMessages,
discussionParticipants
} = state;
const {type, payload} = action;
switch (type) {
case types.SYNCHRONISE_DISCUSSIONS:
{
const oldStudents = discussionStudents
const newStudents = payload.discussionStudents
var parsedStudents = []
oldStudents.forEach((old, i)=>{
if(newStudents.findIndex(newstd => newstd.userId == old.userId) < 0){
parsedStudents.push({
...old,
status: 'inactive'
})
}
})
newStudents.forEach((newStudent, i)=>{
if(parsedStudents.findIndex(pstd => pstd.userId == newStudent.userId) < 0){
parsedStudents.push({
...newStudent,
status: 'active'
})
}
})
var newdiscussionParticipants = payload.discussionParticipants
var newdiscussionGroups = payload.discussionGroups
return Object.assign({}, state, {
discussionStudents: parsedStudents,
discussionParticipants: newdiscussionParticipants,
discussionGroups: newdiscussionGroups
})
}
case REHYDRATE:
{
return {
...state,
rehydrated: true
}
}
}
return state
}