React Router v4-路由渲染属性问题

时间:2018-09-11 20:39:18

标签: react-router

我正在尝试生成许多路线。该代码不会引发错误或任何警告。这就是说,我似乎无法上班。使用articles.map(...)生成的路由都不会显示任何内容。我想知道是否有人可以指出我正确的方向。我想念什么?这是代码段。

function App(props){
    const articles = [
        {id: 1, title: 'title #1', author: 'author #1', date: 'dd/mm/yyyy', post: 'post #1'},
        {id: 2, title: 'title #2', author: 'author #2', date: 'dd/mm/yyyy', post: 'post #2'},
        {id: 3, title: 'title #3', author: 'author #3', date: 'dd/mm/yyyy', post: 'post #3'},
        {id: 4, title: 'title #4', author: 'author #4', date: 'dd/mm/yyyy', post: 'post #4'},
        {id: 5, title: 'title #5', author: 'author #5', date: 'dd/mm/yyyy', post: 'post #5'}
    ];

    return (
        <Router>
            <div className='container'>
                <Navigation />
                <Switch>
                    <Route exact path='/' component={ Home } />
                    <Route exact path='/login' component={ Login } /> 
                    <Route exact path='/signup' component={ Signup } />
                    <Route exact path='/about' component={ About } />
                    {
                        articles.map( entry => { 
                            let {id, title, author, date, post } = entry;

                            console.log(`/article/${id}`);
                            console.log(id, title, author, date, post);

                            <Route
                                 path={`/article/${id}`}
                                 render={
                                     props => <Article {...props} title={title} author={author} date={date} post={post}/>
                                 }  
                            />
                        })
                    }
                </Switch>
            </div>
        </Router>
    ); 
}

这里是git repository

的链接

1 个答案:

答案 0 :(得分:1)

似乎您没有从<Route/>回调中返回map()组件。

在定义多语句=>箭头函数时(如上面代码中的map回调一样),您需要通过return关键字显式返回结果命令arrow函数返回某些内容(即每个<Route/>组件)

尝试以下调整:

{
  articles.map( entry => { 
      let {id, title, author, date, post } = entry;

      console.log(`/article/${id}`);
      console.log(id, title, author, date, post);

      // [ UPDATE ] Add return before <Route
      return (<Route
            path={`/article/${id}`}
            render={
                props => <Article {...props} title={title} author={author} date={date} post={post}/>
            }  
      />)
  })
}

此外,请确保已配置Webpack,以便将bundle.js注入到具有绝对路径的index.html文件中。这将确保您的应用首次从嵌套路由加载时可以对其进行访问。

您可以通过将以下内容添加到output的{​​{1}}配置中来实现:

webpack.config.js
相关问题