drno-reg
@drno-reg
см не кратко

Как правильно реализовать withRouter в реалях react-router-dom@6.0.2 и react-router@6.0.2?

В версии меньше react-router-dom и react-router меньше есть withRouter
и для того чтобы считывать значение userId можно поступить так

ProfileContainer.jsx

import {withRouter} from "react-router-dom"

class ProfileContainer extents React.Component{

componentDidMount(){
       let userId = this.props.match.params.userId;
        if (!userId){
         userId=20771;
        }
        axios.get(`https://social-network.samuraijs.com/api/1.0/profile/`+userId)
            .then(response => {
                // debugger;
                this.props.setUserProfile(response.data);
            });
}

}
let WithUrlDataContainerComponent = withRouter(ProfileContainer);


App.js

<Route path='/profile/:userId'
           render={ () => <ProfileContainer /> } />


НО в версии от 6
import error: 'withRouter' is not exported from 'react-router-dom'


как лучше решить эту проблему?
  • Вопрос задан
  • 5602 просмотра
Пригласить эксперта
Ответы на вопрос 2
drno-reg
@drno-reg Автор вопроса
см не кратко
ProfileContainer.js

import React from "react";
import Profile from "./Profile";
import * as axios from "axios";
import {setUserProfile} from "../../redux/profile-reducer";
import {connect} from 'react-redux';
import {useParams} from "react-router-dom";

const withRouter = WrappedComponent => props => {
    const params = useParams();
    // etc... other react-router-dom v6 hooks
    return (
        <WrappedComponent
            {...props}
            params={params}
            // etc...
        />
    );
};

class ProfileContainer extends React.Component{
    componentDidMount() {
        // debugger;
        //
        console.log(this.props);
        let userId = this.props.params.userId;
        if (!userId){
            userId=2;
        }
        axios.get(`https://social-network.samuraijs.com/api/1.0/profile/`+userId)
            .then(response => {
                // debugger;
                this.props.setUserProfile(response.data);
            });
    }
    render () {
    // debugger;
    return(
<Profile {...this.props}  profile={this.props.profile}/>
    )
  }
}

let mapStateToProps = (state) => ({
    profile: state.profilePage.profile
});

let WithUrlDataContainerComponent = withRouter(ProfileContainer);

export default connect(mapStateToProps, {
    setUserProfile
}) (WithUrlDataContainerComponent);


App.js

<Route path="/profile" element={<ProfileContainer />}>
        <Route path=":userId" element={<ProfileContainer />} />
      </Route>


это 100% работает но не самый лучший способ и нужно делать по-другому но я решаю частную задачу - нужно доделать работу в парадигме IT React Kamasutra версии 2019 года
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы