首页 > 解决方案 > JavaScript 重定向到另一个 JavaScript 页面

问题描述

我有一个名为“Cell.js”的 JS 类,当用户单击按钮时,我想重定向到另一个名为“Detail.js”的 JS 页面。但我不知道如何同时重定向和传递一个变量。我正在研究一个 Pokedex(口袋妖怪列表),当用户单击第一个 ID = 1 的口袋妖怪时,ID 应该被传递到 Detail.js 页面,在该页面中显示所选口袋妖怪的更多详细信息。

Cell.js 代码 =

import React from 'react';
import './Cell.css';
import {ClassDeclaration as pokemon} from "@babel/types";

function Cell({ pokemon }) {
    let id = pokemon.name;
    return (
        <a href={"Detail.js?id= " + id } onclick="passID()">
        <div className="Cell">
            <div className="Cell_img">
                <img src={pokemon.sprites.front_default} alt="" />
            </div>
            <div className="Cell_name">
                {pokemon.name}
            </div>
        </div>
        </a>
    );
}
function passID(){
    return(
        pokemon.id
        );
}
export default Cell;

这是目标 JS 页面“Detail.js”:

import React, {useState} from 'react';
import './Detail.css';

const queryString = window.location.search;
console.log(queryString);
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get('id');

Detail(id)

function Detail(pokemon) {
    return (
            <div className="Detail">
                <div className="Detail_img">
                    <p>TEST</p>
                </div>
                <div className="Detail_name">
                    {pokemon.name}
                </div>
            </div>
    );
}

async function getPoke(id) {
    console.log(id);
    const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
    const json = await res.json();
    console.log(json);
}
export default Detail;

Detail.js 还没有完成,我可以测试任何东西,因为我不知道如何重定向和发送变量。希望你能帮助我 PS:我对 JS xD 很陌生

标签: javascripthtml

解决方案


React 中的导航不会那样发生!React 适用于单页应用程序(SPA)。ReactDOM.render()将加载可以切换不同视图的容器。

推荐的是react-router,但你可以用这种方式进行实验。您可以将任何信息作为道具传递给查看组件(在您的情况下为 id)

import React, { useState } from "react";

const App = () => {
 const [pageNo, setPageNo] = useState(1);
 let id = "Xyz"
 return (
   <div>
     <header>
       <span onClick={() => setPageNo(1)}>View1</span>
       <span onClick={() => setPageNo(2)}>View2</span>
       <span onClick={() => setPageNo(3)}>View3</span>
     </header>

     {loadView(pageNo, id)}
   </div>
 );
};
const loadView = (pageNo, id) => {
 switch (pageNo) {
   case 1:
     return <View1 id={id}/>;
   case 2:
     return <View2 id={id}/>;
   case 3:
     return <View3 id={id}/>;
 }
};

const View1 = ({id}) => <div>View 1 pokeman name = {id}</div>;
const View2 = ({id}) => <div>View 2 pokeman name = {id}</div>;
const View3 = ({id}) => <div>View 3 pokeman name = {id}</div>;

CSS

header {
  border-bottom: 1px solid #c4c4c4;
}
header span {
  margin: 8px;
  cursor: pointer;
  text-decoration: underline;
}

推荐阅读