我设置了一个路由来渲染组件:
<Route exact path="/page/:id" location={this.props.location} key={this.props.location.key} render={({ location }) => (
<PageStart key={this.props.location.key} />
)} />
然后在那个组件(PageStart)中我有:
this.props.match.params.id
但它引发了一个错误:
Cannot read property 'params' of undefined
简单地调用component={}
时传递道具似乎工作正常但不在渲染功能中。为什么呢?
答案 0 :(得分:15)
因为使用render
,您没有将路由器传递的默认道具传递给组件,例如匹配,历史记录等。
当你这样写:
<PageStart key={this.props.location.key} />
这意味着props
组件中没有PageStart
值。
像这样写:
render = {props => <PageStart {...props} key={this.props.location.key} /> } />
现在{...props}
会将所有值传递给PageStart
组件。
答案 1 :(得分:2)
因为您没有将任何match
属性传递给PageStart。您给它key
但没有match
。
试试这个:
<Route
exact
path="/page/:id"
location={this.props.location}
key={this.props.location.key}
render={({
location,
match
}) => (
<PageStart key={this.props.location.key} match={match} />
)}
/>
答案 2 :(得分:2)
错误表明match
道具未定义。这是正确的,这里没有match
道具:
<PageStart key={this.props.location.key} />
所以我们需要传入它。render
函数从react-router接收一堆道具,所有这些都需要向下传递。所以,首先传播它们,然后添加自己的道具:
<Route
exact
path="/page/:id"
location={this.props.location}
key={this.props.location.key}
render={(props) => (
<PageStart {...props} key={this.props.location.key} />
)}
/>
答案 3 :(得分:1)
以我为例,我发现路由器道具中的match
不再是computedMatch
。
IE:this.props.computedMatch.params.id
希望这对某人有帮助!
答案 4 :(得分:1)
请检查提供的路由名称
const AuthNavigattor = createStackNavigator(
{
logins: {screen: LoginScreen},
splash: {screen: SplashScreen},
register: {screen: RegisterScreen},
forgetPassword: {screen: ForgetPasswordScreen},
mobileNumber: {screen: MobileNumberScreen},
codeEnter: {screen: CodeEnterScreen},
changePassword: {screen: ChangePasswordScreen},
// dashboard: { screen: Drawer }
},
{
// initialRouteName: "splash",
headerMode: 'none',
},
);
const ProfileNavigattor = createStackNavigator(
{
logins: {screen: LoginScreen},
splash: {screen: SplashScreen},
register: {screen: RegisterScreen},
forgetPassword: {screen: ForgetPasswordScreen},
mobileNumber: {screen: MobileNumberScreen},
codeEnter: {screen: CodeEnterScreen},
changePassword: {screen: ChangePasswordScreen},
// dashboard: { screen: Drawer }
},
{
// initialRouteName: "splash",
headerMode: 'none',
},
);
此处存在相同路由名称的重新分配,例如登录名,初始名称等,这可能是此错误的原因。重命名此唯一名称将解决您的问题。
答案 5 :(得分:-1)
请尝试这个。我希望它能解决问题。
render = {props => <PageStart {...props} key={this.props.location.key} /> } />