2017-08-31 81 views
1

我正在使用Redux在React本機應用程序上工作。 我是新來的JavaScript /反應語言。React-native Redux - 在onPress上有兩個狀態更改

我使用Auth0在應用上驗證用戶身份,我想管理我的「登錄」/「註銷」按鈕。其實,當我點擊「登錄」按鈕時,字符串在「註銷」上發生變化,但我不知道它是如何回到初始狀態的,在這種情況下,會回到「登錄」字符串。

我authReducer.js

import { 
    BUTTON_LOGOUT, 
    BUTTON_LOGIN 
} from '../actions/types'; 

const INITIAL_STATE = { 
    logButton: 'Log in' 
}; 

export default (state = INITIAL_STATE, action) => { 
    switch (action.type) { 
    case BUTTON_LOGOUT: 
     return { logButton: 'Log out' }; 
    case BUTTON_LOGIN: 
     return { INITIAL_STATE }; 
    default: 
     return state; 
    } 
}; 

我authActions.js

import { BUTTON_LOGOUT, BUTTON_LOGIN } from './types'; 

export const logInToLogOut =() => { 
    return ({ type: BUTTON_LOGOUT }); 
} 

export const logOutToLogIn =() => { 
    return ({ type: BUTTON_LOGIN }); 
} 

我的渲​​染方法LoginForm.js

render =() => { 
    return (
     <Card> 
     <CardSection> 
      <Text style={styles.textStyle}> 
      Login page 
      </Text> 
     </CardSection> 
     <CardSection style={styles.buttonSectionStyle}> 
      <Button onPress={this.props.logInToLogOut} title={this.props.logButton} /> 
     </CardSection> 
     </Card> 
    ); 
    } 

我知道,我只用一個動作裏面「onPress =」但我已經嘗試了很多事情做這件事,這就是爲什麼我保持處理「log i n「到」註銷「,沒有錯誤。

回答

0

我發現我的問題! 我想我不得不寫不好這個切換方法昨天..

toggleButtonLabel =() => { 
    if (this.props.logButton === 'Log in') { 
     this.props.logInToLogOut(); 
    } else { 
     this.props.logOutToLogIn(); 
    } 
    } 
+0

該解決方案在功能上等同於第二個建議,我在我的答案。就這樣你知道。 – jonahe

0

我想你可以做一個切換登錄操作,這兩種狀態之間切換,像這樣

// In the reducer 
case BUTTON_LOGIN_TEXT_TOGGLE: { 
     const previousText = state.logButton; 
     const newText = previousText == 'Log in' ? 'Log out' : 'Login'; 
     return { logButton: newText } 
} 

然後派遣穿過的onClick功能。

根據組件的值this.props.logButton,可以使onClick(onPress?)函數成爲不同的函數。

// inside render 
const {logButton, logInToLogOut, logOutToLogIn} = this.props; 
const onClick = 
    logButton == 'Login' ? logInToLogOut : logOutToLogIn; 

return (
    // other stuff here 
    <Button onPress={onClick} title={logButton} /> 
) 

這兩種解決方案使用the ternary operator,這對於這樣的事情是非常有用的(但可以用if/else語句來代替);