我正在使用 react-router v4,我正试图解决与 react-router / redux / HOC 相关的问题。我有一个更高阶的组件在工作。HOC 本身是connect()
-ed 到 redux 存储。<Route />
如果我通过component
道具将它连接起来,这种方法非常有效:<Route path="/profile" component={ withAuth(Profile) } />
确实有效。
但是,当我尝试对 a<Route />
和渲染道具执行相同操作时,它不起作用:控制台<Route path="/profile" render={ () => withAuth(Profile) } />
抛出“ Route.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
” 当我省略 HOC 时它确实起作用:<Route path="/profile" render={ () => <Profile /> } />
所以我怀疑 HOC 有问题,但我找不到它。
我尝试使用的原因render
是我想将额外的道具传递给 HOC。除此之外,我找不到错误。
任何有新眼光的人都可以看看并让我走上正确的道路吗?谢谢!
/* === app.js === */
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import Header from './header';
import Home from './home';
import Content from './about';
import Profile from './profile';
import withAuth from './withAuth';
import store from '../reducers/store';
export default class App extends Component {
render() {
return (
<Provider store={store}>
<div className="mdl-grid">
<Header />
<main className="mdl-layout__content">
<div className="page-content">
<Route path="/" exact component={Home} />
<Route path="/about" component={Content} />
<Route path="/profile" render={ () => withAuth(Profile) } />
</div>
</main>
</div>
</Provider>
)
}
}
/* === withAuth.js (Higher order component) === */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
const HOC = WrappedComponent => {
return class extends Component {
render() {
if (this.props.auth) {
return <WrappedComponent authenticated={this.props.auth} {...this.props} />
} else {
return <Redirect to="/" />
}
}
}
}
function mapStateToProps({ auth }) {
return { auth };
}
export default WrappedComponent => connect(mapStateToProps)( HOC(WrappedComponent) );