所以我在React Native Cli应用程序中将redux与redux-persist和redux-thunk一起使用。我在“用户”中的第一个状态工作得很好。我添加了另一个带有状态“ posts”的状态,称为“ post”。当我尝试通过在组件中分派一个动作来更新它时,我看到该动作被分派,数据进入有效负载并被发送到我的reducer,但是我的“ posts”保持其初始状态为空。
这是我的“后”减速器:
import UPDATE_POSTS from '../actions/post';
const post = (state = {posts: null}, action) => {
switch (action.type) {
case UPDATE_POSTS:
return {...state, posts: action.payload};
default:
return state;
}
};
export default post;
我的动作:
export const UPDATE_POSTS = 'UPDATE_POSTS';
export const getPosts = (email, token) => {
return async dispatch => {
try {
const config = {
headers: {Authorization: `Bearer ${token}`},
};
const response = await axios.get(
BASE_URL + '/api/posts/' + email,
config,
);
dispatch({type: UPDATE_POSTS, payload: response.data.posts});
} catch (e) {
console.log(e);
}
};
};
我在其中调用动作的componentDidMount():
state = {loading: true};
componentDidMount() {
(async () => {
await getToken();
await getPosts(this.props.user.currentUser.email, this.props.user.token);
this.setState({loading: false});
})();
}
如果我配置有误,请额外配置...
这是我的商店,其中不包括进口商品:
const middleware = applyMiddleware(thunkMiddleware, logger);
const persistConfig = {
key: 'root',
storage: AsyncStorage,
stateReconciler: autoMergeLevel2,
whitelist: ['user'],
};
const pReducer = persistReducer(persistConfig, rootReducer);
export const store = createStore(pReducer, middleware);
export const persistor = persistStore(store);
我的CombineReducers:
import {combineReducers} from 'redux';
import user from './user';
import post from './post';
export default combineReducers({user, post});
App.js:
const App: () => React$Node = () => {
return (
<Provider store={store}>
<PersistGate loading={LoadingView} persistor={persistor}>
<Navigator />
</PersistGate>
</Provider>
);
};
这是我第一次使用redux,已经迷迷了几个小时。如果有人可以帮忙,我将不胜感激!