2016-02-11 168 views
2

我想我错过了一些至关重要的东西。我希望App组件根据状态值注册不同的子项。当点击来自UserType的按钮时,没有任何反应。我可以通过调试看到reducer正在返回更新步骤的状态。但我猜应用程序没有注册状态更改?Redux子不更新父组件状态

减速器/ 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')); 

回答

2

我发现代码中的两个问题,无论是在组件/ app.js

export default connect(mapStateToProps. null)(App); 

有一个 “”而不是简单地通过未定义的“,”。

第二件事情是你的switch语句

switch(this.props.page) {...} 

但是你拥有你终极版店内映射到概率step

const mapStateToProps = (state) => { 
    return { step : state.test.step }; 
}; 

所以,你总是会在默认情况下会在这里结束。所以你应该使用switch(this.props.step)

+1

上帝该死的错别字。谢谢你,先生 –

相关问题