You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Dva+Ant Design Mobile异步请求后状态处理问题

解决Dva中异步请求后的手机号注册状态判断问题

Hey there! Let's work through this phone registration check logic step by step. I see you're already getting the correct API response (with code 221 and the "This phone has been registered" message), so we just need to fix the state mapping and add the conditional Toast trigger logic.

1. 修正mapStateToProps的写法

Your current mapStateToProps has a syntax issue—you don't need the return keyword inside the object literal. Here's the correct way to map the registration state to your component props:

// 方式1:映射整个register模块的状态到组件
const mapStateToProps = (state) => ({
  registerState: state.register
});

// 方式2:只映射需要的code和message字段
const mapStateToProps = (state) => ({
  registerCode: state.register.code,
  registerMessage: state.register.message
});

2. 在组件中处理状态判断逻辑

Once the state is mapped to props, you need to listen for changes after the async API call finishes, then trigger the Toast when the "已注册" condition is met.

类组件写法

If you're using a class component, use componentDidUpdate to detect prop changes:

import { Toast } from 'antd-mobile';
import { connect } from 'dva';

class RegisterComponent extends React.Component {
  // 点击发送验证码的触发方法
  handleSendCode = () => {
    // 触发Dva的异步action,调用手机号检查接口
    this.props.dispatch({
      type: 'register/checkPhone',
      payload: { phone: this.state.phoneInputValue } // 替换为你的手机号输入值
    });
  };

  componentDidUpdate(prevProps) {
    // 检查接口返回的code是否变为221(已注册状态)
    if (this.props.registerCode !== prevProps.registerCode && this.props.registerCode === 221) {
      Toast.info(this.props.registerMessage, 2); // 弹出提示,2秒后自动关闭
    }
  }

  render() {
    return (
      <div>
        {/* 手机号输入框 */}
        <button onClick={this.handleSendCode}>Send Verification Code</button>
      </div>
    );
  }
}

export default connect(mapStateToProps)(RegisterComponent);

函数组件写法(React Hooks)

If you're using a functional component, use useEffect to listen for changes in the mapped props:

import { Toast } from 'antd-mobile';
import { useEffect } from 'react';
import { connect } from 'dva';

const RegisterComponent = ({ dispatch, registerCode, registerMessage }) => {
  const handleSendCode = () => {
    dispatch({
      type: 'register/checkPhone',
      payload: { phone: /* 你的手机号输入值 */ }
    });
  };

  // 监听registerCode和registerMessage的变化
  useEffect(() => {
    if (registerCode === 221) {
      Toast.info(registerMessage, 2);
    }
  }, [registerCode, registerMessage]);

  return (
    <div>
      {/* 手机号输入框 */}
      <button onClick={handleSendCode}>Send Verification Code</button>
    </div>
  );
};

const mapStateToProps = (state) => ({
  registerCode: state.register.code,
  registerMessage: state.register.message
});

export default connect(mapStateToProps)(RegisterComponent);

3. 确保Dva Model正确处理异步请求

Don't forget to verify your Dva model is saving the API response to the state properly. Here's an example model setup:

// models/register.js
export default {
  namespace: 'register',
  state: {
    code: null,
    message: ''
  },
  effects: {
    *checkPhone({ payload }, { call, put }) {
      try {
        // 调用你的手机号检查接口
        const response = yield call(api.checkPhone, payload);
        // 将接口返回的结果存入state
        yield put({
          type: 'saveCheckResult',
          payload: {
            code: response.code,
            message: response.message
          }
        });
      } catch (error) {
        // 处理请求失败的情况
        yield put({
          type: 'saveCheckResult',
          payload: {
            code: -1,
            message: 'Request failed'
          }
        });
      }
    }
  },
  reducers: {
    saveCheckResult(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    }
  }
};

That's all! The core points are correctly mapping the state to your component, listening for changes after the async call, and triggering the Toast when the specific "已注册" code is returned.

内容的提问来源于stack exchange,提问作者user6080689

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:05:04