【发布时间】:2020-02-25 17:21:21
【问题描述】:
我只在LoginAction 中发送了一个动作,但它触发了三个reducer。不知道为什么……
版本:
"react": "16.9.0",
"react-native": "0.61.2",
"react-redux": "^7.1.1",
"redux": "^4.0.4",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.3.0",
这是我的设置。
App.js:
import React from 'react';
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { compose, createStore, applyMiddleware } from 'redux';
// import { persistStore } from 'redux-persist';
// import { PersistGate } from 'redux-persist/integration/react';
import reducers from './src/reducers';
import AppContainer from './src/navigator' // It is my react-navigation route
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const App: () => React$Node = () => {
if (!__DEV__) {
console.log = () => {};
}
const store = createStore(reducers, {}, composeEnhancers(applyMiddleware(ReduxThunk)));
return (
<Provider store={store}>
<AppContainer />
</Provider>
);
};
export default App;
我的 LoginAction.js:
export const testAction = () => {
return (dispatch) => {
dispatch( { type: 'TEST_ACTION' });
}
}
我的减速器设置: reducers/index.js
import { combineReducers } from 'redux';
import LoginReducer from './LoginReducer';
import StoreReducer from './StoreReducer';
import ReservationReducer from './ReservationReducer';
export default combineReducers({
LoginRedux: LoginReducer,
StoreRedux: StoreReducer,
ReservationRedux: ReservationReducer
});
我的 LoginReducer.js:(StoreReducer 和 ReservationReducer 和 LoginReducer 一样)
const INITIAL_STATE = {
...my state arguments
};
export default (state = INITIAL_STATE, action) => {
// Here is my issue !
// StoreReducer is 'StoreReducer reducer =>', action
// ReservationReducer is 'ReservationReducer reducer =>', action
console.log('Login reducer =>', action);
switch (action.type) {
case 'SOME_ACTION':
return {
// state setting from action
};
default:
return state;
}
};
调用action组件是LoginScreen.js:
import React, { Component } from 'react';
import {
// some view
} from 'react-native';
import { connect } from 'react-redux';
import { login, closeLoadingCheckModal, testAction } from '../actions';
class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
// some states
};
}
render() {
return (
<View>
<TouchableOpacity onPress={() => { this.props.testAction() }>
<Text>Press Test Action</Text>
</TouchableOpacity>
</View>
);
}
const mapStateToProps = (state) => {
const { ...some store value } = state.LoginRedux;
return { ...some store value };
};
}
export default connect(mapStateToProps, { login, closeLoadingCheckModal, testAction })(LoginScreen);
当我触发动作时,所有的 reducer 都会被触发。
它应该只是控制台日志Login reducer =>
有人知道我的问题是什么吗?
【问题讨论】:
-
这是预期的行为。所有减速器“看到”每一个动作。他们根据 action.type 决定是否响应。如果您不希望响应特定类型,请不要在该 reducer 中实现该类型。
标签: javascript react-native redux react-redux redux-thunk