簡體   English   中英

在React Native中提交表單后如何導航?

[英]How to navigate after submit a form in react native?

這是我的動作創作者:

export const signInByPhone = ({ phone })=>{
 console.log('All props : ', this.props); // no props are coming. ??  
    return (dispatch) => {        
        fetch(`${API_URL}`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                phone_no : phone
            })
        })
        .then((res) =>res.json())
        .then((jsonRes) =>{
            if (jsonRes.code === 200) {
                console.log('json response code1 : ', jsonRes);
                // go to verification screen                                                                     
                generatOTPSuccess(dispatch,jsonRes);
            }
            else { // reset otp sending screen  
                console.log('json response code2 : ', jsonRes);
            }
        }) 
        .catch(res => generatOTPFail(dispatch, res));
    };    
}

輔助方法:

const generatOTPSuccess = (dispatch, res) =>{   
    dispatch({
        type: 'OTP_GENERATE_SUCCESS',
        payload: res
    });
    this.props.navigation.navigate('OtpVerify');  
  // Error : payload: TypeError: Cannot read property 'navigation' of 
          undefined at generatOTPSuccess                                 
}

我要實現的目標是,一旦OTP成功生成,它應該導航到VerifyScreen。 我無法做到。 誰能說出可能的方式嗎?

在單擊按鈕時,我已通過以下操作:

onButtonPress(){         
        const {phone}=this.props;
  console.log(phone, " :  this.props : ",this.props); // all props r coming
        this.props.signInByPhone({ phone });        
    } 

您的reducer generateOTPSuccess無法訪問組件的this.props

我知道有3種方法可以執行此操作,OTP_GENERATE_SUCCESS(和OTP_GENERATE_FAIL)操作必須更改某些狀態,以便您可以將該狀態傳遞給組件並在組件中發出this.props.navigation.navigate('OtpVerify')調用當您看到更改時(猜測在componentWillUpdate中)

第二種方法是像這樣將回調傳遞給動作創建者。

class Example extends Component
{
    constructor()
    {
        ....   // constructor code
        this.onSuccess = this.onSuccess.bind(this); 
        // this makes sure that this points to the component when it's ran in the action creator

    }

    ....  // component code

    onSuccess()
    {
        this.props.navigation.navigate('OtpVerify');
    }

    handleSubmit(e, loginDetails)
    {
        this.signInByPhone(loginDetails, this.onSuccess);
    }
}

然后我將動作創建者更改為進行onSuccess回調

export const signInByPhone = ({ phone }, onSuccess)=>{
    return (dispatch) => {        
        fetch(`${API_URL}`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                phone_no : phone
            })
        })
        .then((res) =>res.json())
        .then((jsonRes) =>{
            if (jsonRes.code === 200) {
                console.log('json response code1 : ', jsonRes);
                // go to verification screen                                                                     
                generatOTPSuccess(dispatch,jsonRes);
                if(typeof(onSuccess) === 'function')
                {
                    onSuccess();
                }
            }
            else { // reset otp sending screen  
                console.log('json response code2 : ', jsonRes);
            }
        }) 
        .catch(res => generatOTPFail(dispatch, res));
    };    
}

然后將generateOTPSuccess更改為

const generatOTPSuccess = (dispatch, res) =>{   
    dispatch({
        type: 'OTP_GENERATE_SUCCESS',
        payload: res
    });
 }

第三種方法是從獲取中返回承諾並在組件中處理承諾

class Example extends Component
{
    constructor()
    {
        ....   // constructor code
    }

    .... //  component code

    onSuccess()
    {
        this.props.navigation.navigate('OtpVerify');
    }

    onFail()
    {
        ... // handle a fail
    }


    handleSubmit(e)
    {
        this.signInByPhone(loginDetails).then(this.onSuccess, this.onFail);
    }
}

並更改signInByPhone返回承諾

export const signInByPhone = ({ phone }, onSuccess)=>{
    return (dispatch) => {        
        return fetch(`${API_URL}`, {
        .... 
    }
    ....
} 

使用OTP_GENERATE_SUCCESSOTP_GENERATE_FAIL操作更改有效載荷值或在登錄狀態中添加錯誤,以便可以將該狀態傳遞給組件,並在組件的componentWillReceiveProps方法中發出this.props.navigation.navigate('OtpVerify')調用。

例如,您有一個登錄redux

componentWillReceiveProps(newProps) {
    if (newProps.loggedIn) {
      this.props.navigation.navigate('OtpVerify');  
    } else if (!newProps.attempting && newProps.error) {
      showMessage(newProps.error);
    }
  }


const mapStateToProps = (state) => {
  return {
    loggedIn: !!state.login.payload,
    error: state.login.error,
    attempting: state.login.attempting
  }
};

const mapDispatchToProps = (dispatch) => {
  return {}
};

export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen)

並且你的化簡器在不同的動作上會有類似的邏輯,它將以以下方式更新狀態

// login attempts
const attempt = (state, action) =>
  state.merge({attempting: true});

// successful logins
const success = (state, action) =>
  state.merge({attempting: false, error: null, payload: action.payload});

// login failure
const failure = (state, action) =>
  state.merge({attempting: false, error: action.error});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM