我想我在这里缺少一些至关重要的东西。我希望App组件根据状态值注册不同的子项。单击UserType中的按钮时,没有任何反应。我可以通过调试看到reducer正在返回具有更新步骤的状态。但我猜App没有注册状态变化?
减速器/ index.js
import { combineReducers } from 'redux';
import { UPDATE_STEP, INIT } from '../actions';
const INITIAL_STATE = { step : 1 };
function testReducer(state = INITIAL_STATE, action){
console.log('reducing the actions');
console.debug('Working with', action.type);
switch(action.type) {
case UPDATE_STEP:
return {
...state,
step : state.step + 1
};
default:
return state;
}
}
const rootReducer = combineReducers({
test : testReducer
});
export default rootReducer;
动作/ index.js
export const UPDATE_STEP = 'UPDATE_STEP';
export function updateStep(step) {
return {
type : UPDATE_STEP,
step
};
}
组件/用户type.js
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { updateStep } from '../actions';
class UserType extends React.Component {
onClick() {
this.props.updateStep(2);
}
render() {
return (
<div>
<p>Hai</p>
<button onClick={ this.onClick.bind(this) }>Click Me</button>
</div>
)
}
}
export default connect(null, { updateStep })(UserType);
组件/ app.js
import React from 'react';
import { connect } from 'react-redux';
import UserType from './user-type';
import Test from './test';
class App extends React.Component {
render() {
switch(this.props.page) {
case 1:
return <UserType />;
case 2:
return <Test />;
default:
return <UserType />;
}
}
}
const mapStateToProps = (state) => {
return { step : state.test.step };
};
export default connect(mapStateToProps. null)(App);
的src / index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import App from './components/app';
import reducers from './reducers';
let store = createStore(reducers);
ReactDOM.render(
<Provider store={ store }>
<App />
</Provider>
, document.querySelector('#view-container'));
答案 0 :(得分:2)
我在代码中发现了两个问题,包括components / app.js
export default connect(mapStateToProps. null)(App);
有一个“。”而不是简单地通过未定义的“,”。
第二件事是你的开关陈述
switch(this.props.page) {...}
但是您将redux-store映射到概率step
const mapStateToProps = (state) => {
return { step : state.test.step };
};
因此,您将始终以默认情况结束此处。所以你应该使用switch(this.props.step)
代替。