2017-09-13 103 views
1

我想在我的註冊頁面中使用終極版,所以我創建了一個用戶減速器:終極版mapStateToProps連接不正確

const user = (state = initialState, action) => { 
    switch (action.type) { 
     case 'TYPE_FIRSTNAME': 
      console.log('typed first name ' + action.text); 
      return { ...state, firstName: action.text }; 
     case 'TYPE_LASTNAME': 
      return { ...state, lastName: action.text }; 
     case 'TYPE_EMAIL': 
      return { ...state, email: action.text }; 
     case 'TYPE_PASSWORD': 
      return { ...state, password: action.text }; 
     default: 
      return state; 
    } 
} 

它創建這樣的:

const AppReducer = combineReducers({ 
     nav, 
     user 
    }); 
export default AppReducer; 

導航減速是對於導航(與反應導航一起使用,它工作正常)。之後,我創建了一個容器:

const mapStateToProps = state => { 
    return { 
     firstName: state.firstName, 
     lastName: state.lastName, 
    } 
}; 
const mapDispatchToProps = (dispatch, ownProps) => ({ 
    typeFirstName: (text) => {console.log('typed firstname'); 
    dispatch({type: 'TYPE_FIRSTNAME', text})}, 
    typeLastName: (text) => dispatch({type: 'TYPE_LASTNAME', text}), 
    registerUser:() => { 
     //register("mamad"); 
     console.log('called register user : ');   
     dispatch({type: 'MAINSCREEN'}) 
    } 
}); 

export default connect(mapStateToProps, 
    mapDispatchToProps)(RegisterScene) 

但它從來沒有被調用,爲什麼?

+0

你是說如果你把一個調試器放在''mapStateToProps'中的'return {'行中,它永遠不會被命中? –

+0

什麼都不叫?如果你打電話給類似'typeFirstName'的動作創作者,請告訴我們你可以將代碼 –

+0

添加到codesandbox.io – Deano

回答

2

我發現的唯一的問題是mapStateToProps。我認爲它應該是

const mapStateToProps = state => { 
    return { 
     firstName: state.user.firstName, 
     lastName: state.user.lastName, 
    } 
}; 

如果你把錯誤日誌放在這裏會很有幫助。

2

當你組合reducer時,狀態被放入指定的狀態分支。

在你的情況下,你需要state.user

所以你mapStateToProps功能應該像這樣:

const mapStateToProps = state => { 
    return { 
     firstName: state.user.firstName, 
     lastName: state.user.lastName, 
    } 
}; 
+0

非常感謝,它現在的作品:) – Mamadou