Изменить данные на панели навигации при выходе из системы и войти с другой учетной записью - PullRequest
0 голосов
/ 21 января 2019

Цель: Я хочу поставить firstName и lastName на мой Navbar.Итак, я использую запрос axios по id с userId

EDIT: Благодаря @Isaac у меня больше нет бесконечного цикла, когда я сейчас использую componentWillUpdate ().

Проблема: Данные не изменяются (firstName и lastName) при выходе из системы и входе в систему с другой учетной записью

Нет проблем с серверов.

вот изображение: enter image description here Описание: Я вошел в систему как a & g (firstName и lastName), затем я вышел из системы и вошел как j & j.

navbar.js:

import React, { Component } from 'react';
import { fade } from '@material-ui/core/styles/colorManipulator';
import { withStyles } from '@material-ui/core/styles';
import { connect } from 'react-redux';
import AuthA from '../store/actions/AuthA';
import { withRouter } from 'react-router-dom';
import '../Navbar.css';
import NavbarV from './NavbarV';
import PropTypes from 'prop-types';
import axios from 'axios';

class NavbarC extends Component {

  constructor(props){
    super(props);
     this.state = {
       client:[]
    }
  }


  componentWillMount(){
    this.getUser();
  }

  getUser(){
 axios.get (`http://localhost:3002/api/clients/${localStorage.getItem("userId")}?access_token=${localStorage.getItem("token")}`)
    .then(res => {
      this.setState({client: res.data}, () => {
        console.log(this.state)
      })
    })
  }

shouldComponentUpdate(nextState){
  return (this.state.client.firstName !== nextState.firstName || 
this.state.client.lastName !== nextState.lastName);
}

  componentWillUpdate(){
    this.getUser();
    console.log(this.state)
  }

  logout = () => {
    this.props.authfn.logout();
  };

    render() {

        return(
            <NavbarV logout = {this.logout}
           firstName={this.state.client.firstName}
           lastName={this.state.client.lastName}
           userId={this.props.userId}
            auth = {this.props.auth}
            classes={this.props.classes}/>
        )
    }
}

NavbarC.propTypes = {
  auth: PropTypes.bool.isRequired,
  firstName: PropTypes.string.isRequired,
  lastName: PropTypes.string.isRequired
};

const mapStateToProps = (state) => {
  return {
    auth: state.AuthR.auth,
    firstName: state.AuthR.firstName,
    lastName: state.AuthR.lastName,
    userId: state.AuthR.userId
  };
};

const mapDispatchToProps = dispatch => {
  return {
    authfn: AuthA(dispatch)
  }
};

export default connect(mapStateToProps, mapDispatchToProps) (withStyles(styles)(withRouter(NavbarC)));

Если у кого-то есть решение или какие-либо вопросы, я здесь :) Спасибо всем заранее

Ответы [ 2 ]

0 голосов
/ 29 января 2019

Я решаю это!

Это решение:

 componentDidMount(){
    this.setState({ 
      userId: localStorage.getItem("userId"),
      token: localStorage.getItem("token")
    }, () => {
      this.getUser();
    })
  }

  getUser = () => {
 axios.get (`http://localhost:3002/api/clients/${this.state.userId}?access_token=${this.state.token}`)
    .then(res => {
      this.setState({ client: res.data, userId: localStorage.getItem("userId") }, () => {
        console.log(this.state)
      })
    })
  }

  componentDidUpdate(prevProps, prevState){
    if(prevState.userId !== this.props.userId) {
      this.setState({ userId: this.props.userId }, () => {
        this.getUser();
      })
    }
  }
0 голосов
/ 21 января 2019

Прежде всего, вам следует избегать жизненного цикла componentWillUpdate, так как он устарел.

А для вашего случая this.getUser(); будет запущен для получения данных, которые затем вызывают this.setState({client: res.data}). Когда приложение выполнит this.setState(), ваш компонент будет повторно визуализирован, поэтому нет необходимости иметь какой-либо другой componentLifeCycle.

class NavbarC extends Component {

  state = { client:[], userID: null, token: null };


  componentDidMount(){
    this.setState({ 
      userID: localStorage.getItem("userId"),
      token: localStorage.getItem("token")
    }, () => {
      this.getUser();
    })
  }

  getUser(){
 axios.get (`http://localhost:3002/api/clients/${this.state.userID}?access_token=${this.state.token}`)
    .then(res => {
      this.setState({ client: res.data }, () => {
        console.log(this.state)
      })
    })
  }

  componentDidUpdate(prevProps, prevState){
    if(prevState.userID !== this.state.userID) {
      this.getUser();
    }
  }

  logout = () => this.props.authfn.logout();

  render() {

    return(
      <NavbarV 
        logout = {this.logout}
        firstName={this.state.client.firstName}
        lastName={this.state.client.lastName}
        userId={this.props.userId}
        auth = {this.props.auth}
        classes={this.props.classes} />
    )}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...