我正在创建Reactive原住民应用,与Redux。虽然一切都在运行,但初始状态未被填充,调度也不起作用。请帮帮忙。
App.tsx
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import saga from 'redux-saga';
import { appReducer } from './src/store/reducers';
import rootSaga from './src/store/sagas';
import { Counter } from './src/components/counter/counter';
// The middlewares which will be used in this App
const middlewares = [] as any;
// Initialize the saga middleware
const sagaMiddleware = saga();
middlewares.push(sagaMiddleware);
const store = createStore(
appReducer,
applyMiddleware(...middlewares)
);
sagaMiddleware.run(rootSaga);
export const App = () => {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}index.ts (减速器)
import { ActionType } from 'typesafe-actions';
import { combineReducers } from 'redux';
import { CounterActionTypes, CounterState } from '../../constants/action-types';
import { counterReducer } from './counterReducer';
// The top-level state object
export interface ApplicationState {
readonly counter: CounterState
}
export type CounterAction = ActionType<typeof CounterActionTypes>
export const appReducer = () => combineReducers({
counter: counterReducer
});counterReducer.ts
import { CounterActionTypes, CounterState } from '../../constants/action-types';
import { Reducer } from 'redux';
import { ActionType } from 'typesafe-actions';
import { counterActions } from '../actions/index';
export type CounterActions = ActionType<typeof counterActions>;
export const counterInitialState: CounterState = {
count: 1000,
};
export const counterReducer: Reducer<CounterState, CounterActions> = (
state = counterInitialState,
action,
): CounterState => {
switch (action.type) {
case CounterActionTypes.INCREASE:
return {
...state,
count: state.count + 1
};
case CounterActionTypes.DECREASE:
return {
...state,
count: state.count - 1
};
default:
return state;
}
};counter.tsx (组件计数器状态总是未定义)
import {
Button,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { increase } from '../../store/actions/counterActions';
import { ApplicationState } from '../../store/reducers';
import React, { useState } from 'react';
export const Counter = () => {
const count = useSelector((state: ApplicationState) => state.counter?.count);
const dispatch = useDispatch();
return (<>
<View style={{alignItems: 'center', justifyContent: 'center', width: 30,}}>
<TouchableOpacity>
<Text>-{count}-</Text>
</TouchableOpacity>
<Button title='Click here to increase' onPress={() => dispatch( increase())} ></Button>
<TouchableOpacity>
<Text>async up</Text>
</TouchableOpacity>
</View>
</>)
}我不得不把state.counter?.count放进去,这样它就不会坏了。它应该有初始值,但它没有?为什么?
发布于 2022-01-31 19:08:44
我只看了一下代码,但我认为问题在于您的appReducer。我不认为它应该被包装在一个函数中。
因此,与其:
export const appReducer = () => combineReducers({
counter: counterReducer
});尝试:
export const appReducer = combineReducers({
counter: counterReducer
});https://stackoverflow.com/questions/70930648
复制相似问题