【问题标题】:Wrapping a React Route render component in a HOC在 HOC 中包装 React Route 渲染组件
【发布时间】:2020-10-11 19:32:15
【问题描述】:

我将 Profile 组件包装在一个 HOC 中,该 HOC 应该将用户在此路由中注销后重定向到某个页面,如下所示:

           <Route
                path="/profile/:username"
                  render={props=> withAuth(<Profile currentUser={currentUser} {...props} />)}
            />
           

我收到此错误:

错误:对象作为 React 子对象无效(发现:对象与键 {$$typeof, type, compare, WrappedComponent, displayName})。如果您打算渲染一组子项,请改用数组。

这是我的 HOC:

import React, { Component } from "react";
import { connect } from "react-redux";


export default function withAuth(ComponentToBeRendered) {
    class Authenticate extends Component {
        componentDidMount() {
            if (this.props.isAuthenticated === false) {
                this.props.history.push("/signin");
            }
        }
        componentWillUpdate(nextProps) {
            if (nextProps.isAuthenticated === false) {
                this.props.history.push("/signin");
            }
        }
        render() {
            
            return ComponentToBeRendered ;
        }
    }
    function mapStateToProps(state) {
        return {
            isAuthenticated: state.currentUser.isAuthenticated
        }
    }
    
    return connect(mapStateToProps)(Authenticate);
}

这是我的个人资料组件:

import MessageList from "../containers/MessageList";
import UserAside from "./UserAside";
import { connect } from 'react-redux';
import { selectTheUser } from '../store/selectors'

const Profile = props => {
    return (
        <div className="row">
            <MessageList {...props} />
            <UserAside
                {...props} />
        </div>
    )
}

const mapStateToProps = (state, props) => ({
    userToVisit: selectTheUser(props.match.params.username)(state)
})
export default connect(mapStateToProps)(Profile);

【问题讨论】:

    标签: react-router


    【解决方案1】:

    在你的 HOC 中

    render() {
        
        return <ComponentToBeRendered {...this.props}/> ;
    }
    

    在你的路由器中

       const ProfileWithAuth = withAuth(Profile)
       <Route
            path="/profile/:username"
              render={props=> (<ProfileWithAuth currentUser={currentUser} {...props}/>)}
        />
    

    【讨论】:

      猜你喜欢
      • 2022-08-22
      • 2019-09-20
      • 2018-05-30
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      相关资源
      最近更新 更多