我尝试使用 redux 和 Switch 重现所描述的问题,但我遇到的唯一问题是 switch 是保留字,因此我将其更改为 switchState。如果有人需要工作示例:
js/actions/actionTypes.js
export const TRIGGER_SWITCH = 'TRIGGER_SWITCH';
js/actions/switchActions.js
import { TRIGGER_SWITCH } from './actionTypes';
export const triggerSwitch = value => ({
type: TRIGGER_SWITCH,
currentValue: value
});
js/reducers/switchReducer.js
import { TRIGGER_SWITCH } from '../actions/actionTypes';
const initialState = {
currentValue: false
};
const switchReducer = (state = initialState, action) => {
switch(action.type) {
case TRIGGER_SWITCH:
return {
currentValue: action.currentValue
};
default:
return state;
}
};
export default switchReducer;
js/store.js
import {
createStore,
applyMiddleware,
combineReducers
} from 'redux';
import { createLogger } from 'redux-logger';
import switchReducer from './reducers/switchReducer';
const logger = createLogger();
export default (initialState = {}) => (
createStore(
combineReducers({
switchState: switchReducer
}),
initialState,
applyMiddleware(logger)
)
);
js/components/App.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Switch
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this._handleSwitch = this._handleSwitch.bind(this);
}
_handleSwitch(value) {
this.props.actions.triggerSwitch(value);
}
render() {
const { switchState } = this.props;
return (
<View style={styles.container}>
<Switch
onValueChange={this._handleSwitch}
value={switchState.currentValue}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
js/containers/App.js
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { triggerSwitch } from '../actions/switchActions';
import App from '../components/App';
const mapStateToProps = state => ({
switchState: state.switchState
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators({
triggerSwitch
}, dispatch)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
index.ios.js
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { Provider } from 'react-redux';
import createStore from './js/store';
import App from './js/containers/App';
const store = createStore();
const SwitchTest = () => (
<Provider store={store}>
<App />
</Provider>
);
AppRegistry.registerComponent('SwitchTest', () => SwitchTest);
export default SwitchTest;
package.json 依赖项
"dependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.46.4",
"react-redux": "^5.0.5",
"redux": "^3.7.2",
"redux-logger": "^3.0.6"
},