我試圖用終極版,並切換到重現所描述的問題,但我唯一的問題是,開關是一個保留字,所以我把它改成switchState。如果有人需要的工作示例:
JS /動作/ actionTypes.js
export const TRIGGER_SWITCH = 'TRIGGER_SWITCH';
JS /動作/ switchActions。JS
import { TRIGGER_SWITCH } from './actionTypes';
export const triggerSwitch = value => ({
type: TRIGGER_SWITCH,
currentValue: value
});
JS /減速器/ 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 /組件/ 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 /容器/ 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"
},
測試一下默認情況下,好像它被稱爲'TRIGGE之後R_SWITCH' – Maxx
使用'_handleSwitch =(value)=> {this.props.actions.triggerSwitch(value)}' – stereodenis
@Maxx是不是我的redux設置不正確?請看看這個http://stackoverflow.com/questions/39235637/react-native-why-isnt-redux-correctly-updating-the-state –