【发布时间】:2020-10-26 00:11:40
【问题描述】:
我似乎无法弄清楚为什么我无法更新计数器,即使我正在调度正确的操作类型并且它们属于 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;
}
};
【问题讨论】:
标签: javascript reactjs react-native redux