从一个 ID 页面链接到另一个 ID 页面

时间:2021-05-07 04:07:56

标签: reactjs react-router

我的 react-router 有问题。我有一个显示用户信息的 ID 页面,其 URL 类似于 members/:id

enter image description here 这是我的 Author.js,用于从 url 获取用户 ID 并从后端获取信息:

import React from 'react'
import Nav from '../components/Nav.js'
import Footer from '../components/Footer'
import FixedNav2 from '../components/FixedNav2'
import '../styles/style.scss'
import {Link} from 'react-router-dom'
class Author extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            author: undefined,
            dataIsReturned :false
        }
    }
    async componentDidMount(){
        console.log(this.props.location.id);
        const pathname = 'http://localhost:4000/members/'+this.props.location.id;
        // console.log(pathname);
        const data = await fetch(pathname);
        const author = await data.json();
        const newDate = new Date(author.date);
        // console.log(newDate);
        const day = newDate.getDate();
        const month = newDate.getMonth()+1;
        const year = newDate.getFullYear();
        // console.log(day,month,year);
        author.date = day+'-'+month+'-'+year;
        // console.log(item.date);
        this.setState({
            author:author,
            dataIsReturned:true
        })  
        // console.log(this.state.author)
    }

    render() {
        const author = this.state.author;
        const dataIsReturned = this.state.dataIsReturned
        console.log(author);
        console.log(dataIsReturned);
        if(!dataIsReturned){
            return <div>LOADING...</div>
        }
        // const recipeInfor = {
        //     pathname: 'recipes/'+this.props.recipeID,
        //     id: this.props.recipeID
        // }
        return (
            <div className="author">
            <Nav/>
            <FixedNav2/>
            <section className="author-container">
                <div className="container">
                    <div className="row">
                        <div className="col-sm-3">
                            <div className="white-block">
                                <div className="my-sidebar">
                                    <div className="my-avatar">
                                        <img src={author.avatar} width="150" height="150" alt="Avatar" className="avatar avatar-150 wp-user-avatar wp-user-avatar-150 photo avatar-default"></img>
                                        <h4>{author.fullname}</h4>
                                        <ul className="list-unstyled list-inline post-share"></ul>
                                    </div>
                                    <ul className="list-unstyled my-menu">
                                        <li>
                                            <div href="/" className="clearfix">
                                                <i className="fa fa-cutlery"></i>
                                                Participating date 
                                                <span className="right-value"> {author.date}</span>
                                            </div>
                                        </li>
                                        <li>
                                            <div href="/" className="clearfix">
                                                <i className="fa fa-book"></i>
                                                Recipes 
                                                <span className="right-value"> {author.recipes.length}</span>
                                            </div>
                                        </li>
                                        <li>
                                            <div href="/" className="clearfix">
                                                <i className="fa fa-heart"></i>
                                                Favourited Recipes 
                                                <span className="right-value"> {author.favouritedRecipes.length}</span>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div className="col-sm-9 single-recipie author">
                            <ul className="nav nav-tabs" role="tablist">
                                <li role="presentation" active>
                                    <a href="#tab_about" role="tab" data-toggle="tab">About Author</a>
                                </li>
                                <li role="presentation">
                                    <a href="#tab_recipies" role="tab" data-toggle="tab">Author Recipes</a>
                                </li>
                                <li role="presentation">
                                    <a href="#tab_fav_recipies" role="tab" data-toggle="tab">Favourited Recipes</a>
                                </li>
                            </ul>
                            <div className="tab-content">
                                <div role="tabpanel" className="tab-pane fade active in" id="tab_about">
                                    <div className="white-block">
                                        <div className="content-inner"></div>
                                    </div>
                                </div>
                                <div role="tabpanel" className="tab-pane fade" id="tab_recipies">
                                    <div className="white-block">
                                        <div className="content-inner">
                                            <h4 className="no-top-margin">{author.username}'s recipes</h4>
                                            <hr/>
                                            {/* <p className="pretable-loading">Loading...</p> */}
                                            <div className="bt-table">
                                                <div className="boostrap-table">
                                                    <div className="fixed-table-toolbar">
                                                        <div className="pull-left-search">
                                                            <input className="form-control" type="text" placeholder="Search for Recipes..."></input>
                                                        </div>
                                                    </div>
                                                    <div className="fixed-table-container">
                                                        <div className="fixed-table-header">
                                                            <table></table>
                                                        </div>
                                                        <div className="fixed-table-body">
                                                            <table data-toggle="table" data-search-align="left" data-search="true" data-classes="table table-striped" className="table table-striped">
                                                                <thead>
                                                                    <tr>
                                                                        <th>
                                                                            
                                                                                <div className="th-inner">Image</div>
                                                                                <div className="fht-cell"></div>
                                                                           
                                                                        </th>
                                                                        <th>
                                                                            
                                                                            <div className="th-inner sortable">Name</div>
                                                                            <div className="fht-cell"></div>
                                                                           
                                                                        </th>
                                                                        <th>
                                                                            <div className="th-inner">Category</div>
                                                                            <div className="fht-cell"></div>
                                                                        </th>
                                                                        <th>
                                                                            <div className="th-inner">Difficulty</div>
                                                                            <div className="fht-cell"></div>
                                                                        </th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody >
                                                                    {
                                                                    author.recipes.map(recipe => {       
                                                                        const recipeInfor = {
                                                                            pathname: 'recipes/'+recipe._id,
                                                                            id:recipe._id
                                                                        };
                                                                        return  <tr className="no-records-found">
                                                                            <th>
                                                                                <Link to={recipeInfor}>
                                                                                <div className="th-inner-route"><img src={recipe.image} alt={recipe.title} width="120" height="80"></img></div>
                                                                                <div className="fht-cell"></div>
                                                                                </Link>
                                                                            </th>
                                                                            <th>
                                                                                <Link to={recipeInfor}>
                                                                                <div className="th-inner-route sortable">{recipe.title}</div>
                                                                                <div className="fht-cell"></div>
                                                                                </Link>
                                                                            </th>
                                                                            <th>
                                                                                <div className="th-inner">{recipe.category}</div>
                                                                                <div className="fht-cell"></div>
                                                                            </th>
                                                                            <th>
                                                                                <div className="th-inner">{recipe.difficulty}</div>
                                                                                <div className="fht-cell"></div>
                                                                            </th>
                                                                        </tr>                     
                                                                    }                                               
                                                                    )
                                                                    }
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                        <div className="fixed-table-pagination"></div>
                                                    </div>
                                                </div>
                                            <div className="clearfix"></div> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div role="tabpanel" className="tab-pane fade" id="tab_fav_recipies">
                                    <div className="white-block">
                                        <div className="content-inner">
                                            <h4 className="no-top-margin">{author.username}'s favourited recipes</h4>
                                            <hr/>
                                            {/* <p className="pretable-loading">Loading...</p> */}
                                            <div className="bt-table">
                                                <div className="boostrap-table">
                                                    <div className="fixed-table-toolbar">
                                                        <div className="pull-left-search">
                                                            <input className="form-control" type="text" placeholder="Search for Recipes..."></input>
                                                        </div>
                                                    </div>
                                                    <div className="fixed-table-container">
                                                        <div className="fixed-table-header">
                                                            <table></table>
                                                        </div>
                                                        <div className="fixed-table-body">
                                                            {/* <div className="fixed-table-loading">Loading, Please wait...</div> */}
                                                            <table data-toggle="table" data-search-align="left" data-search="true" data-classes="table table-striped" className="table table-striped">
                                                                <thead>
                                                                    <tr>
                                                                        <th>
                                                                            <div className="th-inner">Image</div>
                                                                            <div className="fht-cell"></div>
                                                                        </th>
                                                                        <th>
                                                                            <div className="th-inner sortable">Name</div>
                                                                            <div className="fht-cell"></div>
                                                                        </th>
                                                                        <th>
                                                                            <div className="th-inner">Category</div>
                                                                            <div className="fht-cell"></div>
                                                                        </th>
                                                                        <th>
                                                                            <div className="th-inner">Difficulty</div>
                                                                            <div className="fht-cell"></div>
                                                                        </th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody >
                                                                {
                                                                    author.favouritedRecipes.map(recipe =>  {
                                                                        const recipeInfor = {
                                                                            pathname: 'recipes/'+recipe._id,
                                                                            id:recipe._id
                                                                        };          
                                                                        // console.log(recipeInfor);  
                                                                        // console.log(recipe);  
                                                                        return  <tr className="no-records-found">
                                                                            <th>
                                                                                <Link to={recipeInfor} className="link-title">
                                                                                <div className="th-inner-route"><img src={recipe.image} alt={recipe.title} width="120" height="80"></img></div>
                                                                                <div className="fht-cell"></div>
                                                                                </Link>
                                                                            </th>
                                                                            <th>
                                                                                <Link to={recipeInfor}>
                                                                                <div className="th-inner-route sortable">{recipe.title}</div>
                                                                                <div className="fht-cell"></div>
                                                                                </Link>
                                                                            </th>
                                                                            <th>
                                                                                <div className="th-inner">{recipe.category}</div>
                                                                                <div className="fht-cell"></div>
                                                                            </th>
                                                                            <th>
                                                                                <div className="th-inner">{recipe.difficulty}</div>
                                                                                <div className="fht-cell"></div>
                                                                            </th>
                                                                        </tr>                                
                                                                    }                                
                                                                    )
                                                                    }
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                        <div className="fixed-table-pagination"></div>
                                                    </div>
                                                </div>
                                            <div className="clearfix"></div> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            <Footer/>
        </div>
    )}
}
export default Author;

每次我再次点击“Hi {username}”时,URL 都会类似于 members/members/:id

enter image description here

因为我在 Nav.js 上将 pathname 设置为 members/:id

import React from 'react';
import {Link,withRouter} from 'react-router-dom';
import hatChef from '../img/hatChef.png'
import "../styles/style.scss"
import AuthService from "../AuthComponents/authService"
class Nav extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentUser: undefined,
      authorInfor: undefined
    };
    this.logOut = this.logOut.bind(this);
  }
  componentDidMount() {
    const user = AuthService.getCurrentUser();
    // console.log(this.props.location.pathname);
    if (user) {
      const pathname = 'http://localhost:4000/members/'+AuthService.getCurrentUser().id;
      console.log(pathname);
      fetch(pathname).then(response => response.json()).then(data => {
        const newDate = new Date(data.date);
          // console.log(newDate);
        const day = newDate.getDate();
        const month = newDate.getMonth()+1;
        const year = newDate.getFullYear();
        // console.log(day,month,year);
        data.date = day+'-'+month+'-'+year;
        const authorInfor = {
          id:AuthService.getCurrentUser().id,
          pathname: 'members/'+AuthService.getCurrentUser().id,
          // avatar:data.avatar,
          // fullname:data.fullname,
          // username:data.username,
          // favouritedRecipes:data.favouritedRecipes,
          // recipes:data.recipes,
          // date:data.date
          }
          console.log(authorInfor.pathname);
          this.setState({
            currentUser: user,
            authorInfor: authorInfor
          });
        // }
      });
    }
  }
  logOut() {
    AuthService.logout();
  }
  render() {  
    const currentUser = this.state.currentUser;
    const authorInfor = this.state.authorInfor;
    // console.log(currentUser);
    return(
      <nav className="flex flex-jc-sa flex-ai-c">
        <div>
          <a href="/" className="nav__logo flex flex-ai-c">
            <img  className="img1" src={hatChef} alt="chefHat"></img>
            <p>RECIPE</p>
          </a>
          </div>
          {currentUser ? (
          <div className="nav__menu flex flex-ai-c">
            <div className="nav__menu-item"><Link to={authorInfor}><i className="fa fa-user" aria-hidden="true"></i>
                            <span>HI {currentUser.username}</span></Link></div>
            <div className="nav__menu-item"><Link to='/Login' onClick={this.logOut}><i className="fa fa-sign-in" aria-hidden="true"></i>
                            <span>LOG OUT</span></Link></div>
            <div className="nav__menu-item"><Link to='/Submit'><i className="fa fa-user" aria-hidden="true"></i>
                            <span>SUBMIT RECIPE</span></Link></div>
          </div>
          ): (
            <div className="nav__menu flex flex-ai-c">
              <div className="nav__menu-item"><Link to='/Register'><i className="fa fa-user" aria-hidden="true"></i>
                              <span>REGISTER</span></Link></div>
              <div className="nav__menu-item"><Link to='/Login'><i className="fa fa-sign-in" aria-hidden="true"></i>
                              <span>LOG IN</span></Link></div>
          </div>
          )}
      </nav>
    );
  }
}
  
export default withRouter(Nav);

如何链接到 members/:id 而不将 URL 连接到前一个 URL 的 id 部分?

这是我设置的路线:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import {BrowserRouter as Router,Route,Switch} from 'react-router-dom'
import Login from './LoginComponents/Login'
import Submit from './SubmitComponents/Submit';
import Recipe from './RecipesComponents/Recipe'
import RecipeItem from './RecipesComponents/RecipeItem'
import Author from './MemberComponents/Author'
import Members from './MemberComponents/Member'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
  <React.StrictMode>
    <Router>
      <Switch>
        <Route exact path = "/" component={App}/>
        <Route path="/Register" exact component ={Login}/> 
        <Route path="/Login" exact component ={Login}/> 
        <Route path="/Submit" exact component ={Submit}/> 
        <Route path='/recipes' exact component={Recipe}/>
        <Route path='/recipes/:id' exact component={RecipeItem}/>
        <Route path="/members" exact component ={Members}/>
        <Route path="/members/:id" exact component ={Author}/> 
      </Switch>
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
);



1 个答案:

答案 0 :(得分:0)

pathname 设置为 /members/:id 而不是 members/:id(表示“相对于当前网址”)。