gpt4 book ai didi

javascript - React react-router-dom 将 Prop 传递给组件

转载 作者:IT王子 更新时间:2023-10-29 03:16:53 35 4
gpt4 key购买 nike

我需要使用路由器将 Prop 传递给组件。这是我的代码:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import AppBarTop from './appbar/AppBarTop';

import Login from '../pages/login/Login';
import {BrowserRouter as Router, Route} from 'react-router-dom';


class App extends Component {

render() {

const { isAuthenticated } = this.props;

return (
<Router>
<div>
<AppBarTop isAuthenticated={isAuthenticated} />
<div className="content">
<Route path="/login" isAuthenticated={isAuthenticated} component={Login} />
</div>
</div>
</Router>
);
}
}

如您所见,isAuthenticated 是我想传递给登录组件的 Prop 。

class Login extends Component {

constructor(props) {
super(props);
console.log(props);
}

render() {
return (
<LoginForm />
);
}

}

export default connect(null) (Login);

当我记录 Prop 时,isAuthenticated Prop 不存在。我做错了什么?我怎样才能正确传递 Prop ?我遵循了文档和其他讨论。根据我的理解,它应该可以工作。react-routerreact-router-dom 的版本是 4.0.0

最佳答案

像这样传递:

<Route 
path="/login"
render={(props) => <Login {...props} isAuthenticated={isAuthenticated}/>}
/>

它应该可以通过登录组件中的 this.props.isAuthenticated 获得。

{...props} 的原因:

如果我们不写这个,那么只有 isAuthenticated 会被传递给登录组件,路由器传递给组件的所有其他值,在登录组件内将不可用。当我们编写 {...props} 时,我们将传递所有值和一个额外值。

并且不要将 component 与路由器一起使用,而是使用 render 方法。

根据 DOC :

Component :

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render.

Render :

This allows for convenient inline rendering and wrapping without the undesired remounting.

关于javascript - React react-router-dom 将 Prop 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43469071/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com