Reducer在初始化期间返回undefined但在reducer switch中默认返回initialState

时间:2017-07-07 14:30:05

标签: react-native redux react-redux

我试图按照redux-persist docs中的说明延迟渲染,直到补液完成,我现在收到此错误

"Reducer 'auth' returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined."

但是,我在auth reducer中定义并返回initialState,如下所示:

const initialState = {
    authenticated: false,
    authenticating: false,
    loginError: '',
}
export default function reducer(state = initialState, action) {
    switch (action.type) {
        ...my switch cases here

        default:
        return state
    }
}

我没有改变我创建商店的方式,因此我不确定为什么我现在收到此错误。我还将包括我的商店创建和下面的减速器方法

const store = createStore(
    reducers,
    undefined,
    compose(
        applyMiddleware(thunk),
        autoRehydrate({ log: true }),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)

export default class AppProvider extends Component {
  constructor(props) {
    super(props)
    this.state = {
      rehydrated: false,
    }
  }

  componentWillMount() {
    persistStore(store, {storage: AsyncStorage}, () => {
      this.setState({ rehydrated: true })
    })
  }

  render() {
    if (!this.state.rehydrated) {
      return <ActivityIndicator />
    }
    return (
      <Provider store={store}>
      <App/>
      </Provider>
    )
  }
}

我的Redurs导出文件

export default reducers = combineReducers({
    auth,
    connection,
    initialLoad,
    queue,
})

2 个答案:

答案 0 :(得分:0)

这似乎是您商店创作的一部分。 F8App是一个很好的参考。

您可以执行以下操作:

// configureStore.js
// ... imports

const middlewares = [thunk, promise, array];
var createAppStore = applyMiddleware(...middlewares)(createStore);

export default configureStore = (onComplete) => {
    const store = autoRehydrate()(createAppStore)(reducers);
    persistStore(store, { storage: AsyncStorage }, onComplete);
    return store;
}


// AppProvider.js
// ...
    constructor() {
        super();
        this.state = {
            isLoading: true,
            store: configureStore(() => {
                this.setState({ isLoading: false });
            }),
        };
    }
    render() {
        if (this.state.isLoading) {
            return <ActivityIndicator />;
        }
        return (
            <Provider store={this.state.store}>
                <App />
            </Provider>
        );
    }
// ...

答案 1 :(得分:0)

主要原因是您将undefined作为预加载状态传递。只需传入root reducer和中间件,错误就会消失

const store = createStore(
    reducers,
    compose(
        applyMiddleware(thunk),
        autoRehydrate({ log: true }),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)

此外,它抱怨auth未定义,因此您应确保在根reducer reducers中正确导入所有Reducer。