我似乎无法弄清为什么即使我调度正确的操作类型也无法更新计数器,而它们却处于INCREMENT和DECREMENT状态之内。我尝试传递mapDispatchToProps并将函数放入该函数中,但仍然遇到相同的问题,由于某种原因没有任何状态更新。
索引:
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import {reducer} from './src/reducers/counter';
const store = createStore(reducer);
const Main = () => (
<Provider store={store}>
<App />
</Provider>
);
AppRegistry.registerComponent(appName, () => Main);
应用
import {connect} from 'react-redux';
// create a component
class App extends Component {
increment = () => {
this.props.dispatch({type: 'INCREMENT'});
};
decrement = () => {
this.props.dispatch({type: 'DECREMENT'});
};
render() {
return (
<View style={styles.container}>
<Button onClick={this.increment} title={'Add 1'} />
<Text>Counter {this.props.count} </Text>
<Button onClick={this.decrement} title={'Subtract 1'} />
</View>
);
}
}
计数器
const initState = {
count: 1,
};
export const reducer = (state = initState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1,
};
case 'DECREMENT':
return {
count: state.count - 1,
};
default:
return state;
}
};
答案 0 :(得分:1)
这是React Native应用,对吗?您的错误是您为onClick
使用了Button
而不是onPress
。切换道具名称后,It works fine now。
答案 1 :(得分:0)
您必须使用connect
功能将App组件连接到redux存储。
import { connect } from 'react-redux';
// create a component
class App extends Component {
increment = () => {
this.props.increment();
};
decrement = () => {
this.props.decrement();
};
render() {
return (
<View style={styles.container}>
<Button onPress={this.increment} title={'Add 1'} />
<Text>Counter {this.props.count} </Text>
<Button onPress={this.decrement} title={'Subtract 1'} />
</View>
);
}
}
const mapStateToProps = state => ({ count: state.count })
const mapDispatchToProps = dispatch => {
return {
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
答案 2 :(得分:0)
需要注意以下几点才能使其正常工作:
constructor() {
super(props)
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}