将道具传递给React Router 4中的嵌套路由.TypeError:render不是函数

时间:2017-11-03 18:05:38

标签: reactjs react-router

我试图创建这样的嵌套路线,在this之后回答

/--Home
|--campaigns
   |--campaigns/:cid

Index.js

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
    ,
    document.getElementById('root'));
registerServiceWorker();

App.js

class App extends Component {
  render() {
    return (
        <div>
          <Route exact path="/" render={(props) => <Home foo="bar" {...props}/>}/>
          <Route path="/campaigns" render={(props) => <Campaigns foo="bar" {...props}/>}/>
        </div>
    );
  }
}

Home.js

const Home = () => (
    <div>
        Home
    </div>
)

Campaigns.js

const Campaigns = () => (
    <div>
        <Route exact path="/campaigns" render={<div>Campaigns</div>}/>
        <Route path="/campaigns/:cid" render={(props) => <Campaign {...props} foo="bar"/>}/>
    </div>
)

Campaign.js

const Campaign = () => (
    <div>
        <Route path="/campaigns/:cid" render={<div>Campaign 1</div>}/>
    </div>
)

我使用该方法,因为我无法使用该方法将道具传递给组件。

当/ route工作正常时,当我浏览/ campaign时,我得到:TypeError:render不是函数

1 个答案:

答案 0 :(得分:0)

错误非常明显。 render道具接受函数作为其值,而不是元素。所以只需将其更改为:

const Campaigns = () => (
    <div>
        <Route exact path="/campaigns" render={() => <div>Campaigns</div>}/>
        <Route path="/campaigns/:cid" render={(props) => <Campaign {...props} foo="bar"/>}/>
    </div>
);

const Campaign = () => (
    <div>
        <Route path="/campaigns/:cid" render={() => <div>Campaign 1</div>}/>
    </div>
);