2017-08-17 53 views
0

當我嘗試使用HOC包裝呈現組件路由時遇到無限循環。路由渲染方法看起來是這樣的:當在路由中應用HOC無限循環時

const render = (route, additionalProps) => { 
const scrollActive = has(route, "scroll") ? route.scroll : true; 
const Component = scrollActive 
    ? withScrollToTop(route.component) 
    : route.component; 
return props => { 
    return <Component {...props} {...additionalProps} route={route} />; 
}; 

return (
    <Switch> 
    {routes.map((route, i) => { 
     return (
     <Route 
      key={i} 
      path={route.path} 
      exact={route.exact} 
      strict={route.strict} 
      render={render(route, injectProps)} 
     /> 
    ); 
    })} 
    </Switch> 
); 

對於時間感(因爲它是環出),該HOC實際上沒有做,除了與其他類包裝的成分什麼。

export default function withScrollToTop(WrappedComponent) { 
    const displayName = `HigherOrder.WithScrollToTop('${getDisplayName(
    WrappedComponent 
)}')`; 

    class WithScrollToTop extends React.PureComponent { 
    static displayName = displayName; 

    static WrappedComponent = WrappedComponent; 

    render() { 
     const props = Object.assign({}, this.props); 
     return React.createElement(WrappedComponent, props); 
    } 
    } 

    return hoistStatics(WithScrollToTop, WrappedComponent); 
} 

試圖命中任何路由會導致無限循環。

回答

0

你的問題是這條線: render={render(route, injectProps)}(你的沒有最後的})。

這將觸發render函數,它不會將函數傳遞給子代props

+0

對不起,這是從渲染道具中刪除三元組的錯字。我們還有另一個功能可以用工廠進行渲染。更新原始代碼片段以更正丟失的大括號。 – mindlis

+0

是的,正確類型的事件。你應該調用'render = {this.render ...}'或'render = {()=> this.render ...}'。你的綁定方式將馬上執行'render'函數,而不是將'render'傳遞給'props' –