React Router 4,使用无状态组件路由

时间:2017-12-08 10:45:15

标签: javascript reactjs components stateless react-router-dom

如果我想路由到无状态组件,我使用的组件会给我一个匹配参数

e.g。

<Route path="/ingredient/:ingredientID" component={IngredientPage} />

使用“component”属性的问题是我无法传递要使用的类函数。在加载组件之前,我想基于id获取api数据,我希望组件是一个功能组件。

如果我使用渲染我不能调用状态更改,因为它会重新渲染(无限循环)。

  <Route path="/ingredient/:ingredientID" render={(props) => {
    this.loadIngredient(props.match.params.ingredientID) 
    //this will change state which creates a loop
    return <IngredientPage ingredient={this.state.ingredient} />
   } />

到目前为止,我能解决这个问题的唯一方法是让组件成为状态组件,就像它的父组件一样,然后我处理两个状态。

有什么建议吗?

0 个答案:

没有答案