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

如何在无状态组件中通过React Navigation传参触发GraphQL变更

如何在无状态组件中通过React Navigation传递参数并触发GraphQL变更

没问题,我来帮你梳理清楚这个实现步骤!你的思路是完全正确的,用React Navigation的参数传递就能搞定,只是子组件里有个小细节需要调整。

第一步:修正无状态子组件的参数获取

你当前的子组件代码里,navigation.getParam(phoneNumber)这里犯了个小错误——getParam的第一个参数应该是字符串形式的参数名,而不是未定义的变量。调整后就能正确拿到父组件传递的phoneNumber了:

export const AuthenticationCodeModal = (props: NavigationScreenProps) => {
  const { navigation } = props;
  // 这里要把参数名写成字符串'phoneNumber',还可以加个默认值防止参数缺失
  const phoneNumber = navigation.getParam('phoneNumber', ''); 

  return(
    <View style={styles.container}>
      {/* 把拿到的phoneNumber传递给AuthenticationFormContainer */}
      <AuthenticationFormContainer phoneNumber={phoneNumber} />
    </View>
  )
}

第二步:在AuthenticationFormContainer中触发GraphQL变更

接下来,在AuthenticationFormContainer里,你就可以接收这个phoneNumber属性,结合用户输入的验证码来触发认证mutation了。举个示例实现:

// 假设这是AuthenticationFormContainer的实现
export const AuthenticationFormContainer = ({ phoneNumber }) => {
  const [verificationCode, setVerificationCode] = useState('');
  const { mutate: authenticateUser } = useMutation(AUTHENTICATE_MUTATION); // 你的认证mutation

  const handleSubmit = async () => {
    try {
      await authenticateUser({
        variables: {
          phoneNumber,
          verificationCode
        }
      });
      // 认证成功后的逻辑,比如跳转首页
    } catch (error) {
      // 处理错误提示等逻辑
    }
  };

  return (
    <View>
      <TextInput 
        value={verificationCode} 
        onChangeText={setVerificationCode}
        placeholder="输入验证码"
        keyboardType="numeric"
      />
      <Button title="完成认证" onPress={handleSubmit} />
    </View>
  );
};

补充小提示

  • 父组件的传参代码是没问题的,navigation.navigate('Authenticate', { phoneNumber })已经正确把参数带上了;
  • getParam的第二个参数是默认值,建议加上,避免参数未传递时出现undefined的情况;
  • 因为你用的是函数式无状态组件,直接解构props里的navigation就能用,不需要像类组件那样额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:47:06