我有一个正在使用react-redux的功能计数器应用程序。我可以看到每次使用Increment / Decrement函数调度动作时,状态都会更新,但是,我实际上无法输出状态值。
这是我第一次尝试使用模块构建redux应用程序(与使用redux cdn构建html文件相反)。请帮我弄清楚我在做什么错。
谢谢。
//App.js
import { Increment, Decrement } from './redux'
class App extends Component {
render() {
return (
<div className="App">
<h1>{this.props.count}</h1> //Doesn't output anything
<button onClick={this.props.Increment}>+</button>
<button onClick={this.props.Decrement}>-</button>
</div>
);
}
}
const mapStateToProps = state => ({
count: state.count
})
const mapDispatchToProps = {
Increment,
Decrement
}
const AppContainer = connect(
mapStateToProps,
mapDispatchToProps
)(App)
export default AppContainer
//redux.js
import { createStore } from 'redux';
export const Increment = () => {
return {
type: 'INCREMENT'
}
}
export const Decrement = () => {
return {
type: 'DECREMENT'
}
}
export const reducer = (state = 0, action) => {
switch(action.type){
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
export function configureStore(intitalState = 0){
const store = createStore(reducer, intitalState)
return store;
}
export const store = configureStore()
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux';
import { store } from './redux';
import AppContainer from './App';
ReactDOM.render
(<Provider store={store}>
<AppContainer/>
</Provider>, document.getElementById('root'));
答案 0 :(得分:0)
在这种情况下,state
实际上是一个值,而不是将值存储为count
属性的对象。
它应该是:
const mapStateToProps = state => ({
count: state
})
或combineReducers
可用于将特定的reducer映射为商店属性:
const store = createStore(combineReducers({count: reducer }), intitalState)