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

React Native类组件使用react-router-native传location.state报TypeError求助

解决react-router-native升级后Link传state目标组件无法获取location的问题

问题原因

升级react-router-native到v6及以上版本后,路由组件不再自动接收location、history等核心props,这就是你报错Cannot read property 'state' of undefined的根本原因——this.props.location已经不存在了。

解决方案

根据你的类组件场景,提供两种可行方案:

方案1:用withRouter高阶组件包裹类组件

react-router-native v6依然保留了withRouter,用来给类组件注入路由相关props:

  1. 补充导入withRouter:
import { NativeRouter, Route, Link, Redirect, withRouter } from "react-router-native";
  1. 导出目标组件时用withRouter包裹:
class SearchMethodComponent extends React.Component {
  componentDidMount() {
    console.log("Search method mounted")
    // 现在this.props.location可正常访问,建议加默认值避免解构报错
    const { ingreds, more_needed, no_more_needed, initial_data } = this.props.location.state || {};
    if (initial_data !== undefined) {
      this.setState({
        initialData: initial_data,
        ingredients_rough: ingreds,
        moreNeeded: more_needed
      })
    } else {
      this.setState({
        ingredients_rough: ingreds,
        moreNeeded: more_needed
      })
    }
  }

  // 其他组件逻辑...
}

// 关键步骤:用withRouter包裹后导出组件
export default withRouter(SearchMethodComponent);

方案2:重构为函数组件使用useLocation Hook

如果允许重构组件,函数组件的方式更贴合react-router v6的设计思路:

  1. 导入useLocation Hook:
import { useLocation, useEffect, useState } from "react-router-native";
  1. 在组件内获取location并处理逻辑:
function SearchMethodComponent() {
  const location = useLocation();
  const [state, setState] = useState({
    initialData: null,
    ingredients_rough: [],
    moreNeeded: false
  });

  useEffect(() => {
    console.log("Search method mounted")
    const { ingreds, more_needed, no_more_needed, initial_data } = location.state || {};
    if (initial_data !== undefined) {
      setState({
        initialData: initial_data,
        ingredients_rough: ingreds,
        moreNeeded: more_needed
      })
    } else {
      setState({
        ingredients_rough: ingreds,
        moreNeeded: more_needed
      })
    }
  }, []);

  // 其他组件逻辑...
}

验证Link写法

你当前的Link写法符合v6规范,无需修改:

<Link to="/search-method/" state={{ ingreds: ingreds, more_needed: true }}>跳转</Link>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:35:10