簡體   English   中英

如何在反應中將道具從路由數組傳遞給組件

[英]how to pass props into component from route array in react

現在我定義路由"react-router-dom": "^5.1.1",像這樣:

const Channel = loadable(() => import(/* webpackChunkName: 'about' */ '@/views/App/Cruise/Channel'))


const routes = [
    { path: '/index', exact: true, name: 'Index', component: Channel, auth: [1] }
]

對於舊方式,我像這樣將道具傳遞給組件:

class App extends React.Component {
    render() {
        return (<Router>
            <Switch>
                <Route path='/login' render={(props) => <Login user={this.props.user} />}/>
            </Switch>
        </Router>)
    }
}

將路由定義為數組時如何將道具傳遞給組件通道? 我試過這樣:

{ 
        path: '/app/cruise/channel', 
        exact: false, 
        name: 'Channel', 
        render: (props) => (<Channel {...props} channel={this.props.channel}/>)
    },

但它無法正常工作。 現在我在路由外部組件中傳遞了這樣的道具:

<Content className='content'>
                        <Switch>
                            {routes.map(item => {
                                return (
                                    <Route
                                        key={item.path}
                                        path={item.path}
                                        exact={item.exact}
                                        render={props =>
                                            !auth ? (
                                                <item.component {...props} channel = {this.props.channel}/>
                                            ) : item.auth && item.auth.indexOf(auth) !== -1 ? (
                                                <item.component {...props} channel = {this.props.channel} />
                                            ) : (
                                                <Redirect to='/404' {...props} />
                                            )
                                        }></Route>
                                )
                            })}
                            <Redirect to='/404' />
                        </Switch>
                    </Content>

它可以工作,但我認為這是一種非常丑陋的方式,有更好的建議嗎?

我相信您會使用 Link 組件路由到正確的位置。 所以你可以使用路由和鏈接如下

 const Channel = loadable(() => import(/* webpackChunkName: 'about' */ '@/views/App/Cruise/Channel'))


const routes = [
    { path: '/index', exact: true, name: 'Index', component: Channel, auth: [1] }
]

APP內鏈接

const App=(props)=>{

return (
<Link to={{
              pathname:'/index',
              user:props.user
            }} >Channel
</Link>
)

}

在頻道內,您可以從 props.location.user 訪問用戶

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM