react-router6.0 路由state传参并接收

Message/index.jsx

import React, { Component } from "react";
import { Link, Route, Routes } from "react-router-dom";
import Detail from "./Detail";
class News extends Component {
  state = {
    messageArr: [
      { id: "1", title: "消息1" },
      { id: "2", title: "消息2" },
      { id: "3", title: "消息3" },
      { id: "4", title: "消息4" },
    ],
  };
  render() {
    const { messageArr } = this.state;
    return (
      <div>
        <ul>
          {messageArr.map((msgObj) => {
            return (
              <li key={msgObj.id}>
                {/*向路由组件传递params参数*/}
                {/* <Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link> */}
                {/*向路由组件传递search参数*/}
                {/* <Link
                  to={`/home/message/detail?id=${msgObj.id}&title=${msgObj.title}`}
                >
                  {msgObj.title}
                </Link> */}
                &nbsp;&nbsp;
                {/*向路由组件传递state参数*/}
                <Link
                  to={`/home/message/detail`}
                  state={{ id: msgObj.id, title:msgObj.title}}
                >  {msgObj.title}</Link>
              </li>
            );
          })}
        </ul>
        <hr />
        <Routes>
          {/**声明接收params参数 */}
          {/* <Route path="detail/:id/:title" element={<Detail />}></Route> */}

          {/**search参数无需声明接收,正常注册路由即可 */}
          {/* <Route path="detail" element={<Detail />}></Route> */}

          {/**向路由组件chuandistate参数*/}
          <Route path="detail" element={<Detail />}></Route>
        </Routes>
      </div>
    );
  }
}

export default News;

Detail/index.jsx

import React from "react";
import { useLocation} from 'react-router-dom';
import qs from 'querystring'

let obj={name:'tome',age:18}
console.log(qs.stringify(obj));

let str='carName=奔驰&price=1999999'
console.log(qs.parse(str));

const detailData = [
  { id: "1", content: "你好,中国",title:"苹果" },
  { id: "2", content: "你好,小可爱",title:"苹果" },
  { id: "3", content: "你好,未来的你",title:"苹果" },
  { id: "4", content: "你好,未来的你s",title:"苹果" },
];

const Detail = () => {
  //接收params参数
  // const params = useParams();
  // const findResult=detailData.find((detailObj)=>{
  //   return detailObj.id===params.id
  // })

  //接收search参数
  // const {search}=this.props.location;
  // const {id,title}=qs.parse(search.slice(1));

  // const { search } = useLocation();
  // const {id,title}=qs.parse(search.slice(1));

  //接收state参数
  const stateparams=useLocation();
  const {id,title}=stateparams.state;

  const findResult=detailData.find((detailObj)=>{
    return detailObj.id===id
  })||{}
  return (
    <div>
      <ul>
        <li>ID:{findResult.id}</li>
        <li>TITLE:{findResult.title}</li>
        <li>CONTENT:{findResult.content}</li>
      </ul>
    </div>
  );
}

export default Detail;

上一篇:c#QQ连连看辅助


下一篇:如何手动安装Google API