我无法让简单的React和Redux示例正常工作,需要一些帮助。我尝试分派incrementNumber操作时,我收到以下错误。我将在下面粘贴我的代码。 Or you can use the Github link here.提前致谢!
index.js(App root)
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import store from './store/configureStore';
import App from './containers/App';
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
configureStore.js
import { createStore } from 'redux';
import rootReducer from '../reducers';
export default createStore(rootReducer);
index.js(root reducer)
import { combineReducers } from 'redux';
import numbersReducer from './numbersReducer';
const rootReducer = combineReducers({
number: numbersReducer
});
export default rootReducer;
numbersReducer.js
import initialState from './initialState';
export default function numbersReducer(state = initialState.number, action) {
switch (action.type) {
case "INCREMENT_NUMBER":
return { ...state, number: state.number + 1 }
default:
return state;
}
}
initialState.js
export default {
number: 0
}
App.js
import React from 'react';
import { connect } from 'react-redux';
import { incrementNumber } from '../actions/appActions';
export class App extends React.Component {
componentDidMount() {
this.props.dispatch(incrementNumber(1));
}
render() {
return (
<div>
Current number: {this.props.number}
</div>
);
}
}
const mapStateToProps = state => ({
number: state.number
});
export default connect(mapStateToProps)(App);
appActions.js
export function incrementNumber(number) {
return { type: "INCREMENT_NUMBER", number}
}
答案 0 :(得分:1)
<div>
Current number: {this.props.number.number}
</div>
并且也改变了这一点。
export default function numbersReducer(state = initialState, action) {
switch (action.type) {
case "INCREMENT_NUMBER": {
return { ...state, number: state.number + 1 }
}
default:
return state;
}
}
/ * state = initialState * /
答案 1 :(得分:0)
const rootReducer = combineReducers({
number: numbersReducer
});
在combineReducers
参数对象中,"number"
不能为属性。因为numbersReducer
在其"number"
中已经具有此属性initialState
。