在本机中提交表单后如何导航?

时间:2017-09-17 06:21:24

标签: reactjs react-native react-redux react-navigation

这是我的动作创建者:

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 });        
    } 

2 个答案:

答案 0 :(得分:0)

您的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
    });
 }

第三种方法是从fetch返回promise并在组件中处理它

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}`, {
        .... 
    }
    ....
} 

答案 1 :(得分:0)

使用OTP_GENERATE_SUCCESSOTP_GENERATE_FAIL操作更改有效负载值或在登录状态中添加错误,这样您就可以将该状态传递给组件并在组件中发出this.props.navigation.navigate('OtpVerify')来电&#39 ; s componentWillReceiveProps方法。

例如,您有一个登录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)

并且你的reducer将在不同的动作上具有类似的逻辑,它将以下列方式更新状态

// 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});