2017-08-17 63 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' –