周大胖子 发表于 2022-7-1 10:00:07

React 路由传参 三种

本帖最后由 周大胖子 于 2022-7-1 10:03 编辑

第一种传参模式 基础 URL key value 传参:

<Link className="nav" to={`/b/child2?age=20&name=zhangsan`}>Child2</Link>

//注册路由(无需声明,正常注册即可):
<Route path="/b/child2" component={Test}/>
      
//接收参数方法1:
import { useLocation } from "react-router-dom";
import qs from "query-string";
const { search } = useLocation();
//search参数 => {age: "20", name: "zhangsan"}

//接收参数方法2:
import { useSearchParams } from "react-router-dom";
const = useSearchParams();
// console.log( searchParams.get("id")); // 12




第二种传参模式: 占位符传参。类似于PHP等后端的 路由参数传递方式


//路由链接(携带参数):
<Link to={{ pathname:`/b/child1/${id}/${title}` }}>Child1</Link>
//或 <Linkto={`/b/child1/${id}/${title}`}>Child1</Link>

//注册路由(声明接收):
<Route path="/b/child1/:id/:title" component={Test}/>
   
//接收参数:
import { useParams } from "react-router-dom";
const params = useParams();
//params参数 => {id: "01", title: "消息1"}




第三种state参数传参:

3.1 function 传参 模式

//通过Link的state属性传递参数
<Link
   className="nav"
   to={`/b/child2`}
   state={{ id: 999, name: "i love merlin" }}
>
    Child2
</Link>

//注册路由(无需声明,正常注册即可):
<Route path="/b/child2" component={Test}/>
   
//接收参数:
import { useLocation } from "react-router-dom";
const { state } = useLocation();
//state参数 => {id: 999, name: "我是梅琳"}

//备注:刷新也可以保留住参数



3.2如何在class 的函数类中使用 useLocation


export const withNavigation = (PureComponent) => {
    return (props) => <PureComponent {...props} navigate={useNavigate()}   lstate={useLocation()}/>;
};




class CssModelTest extends React.PureComponent{
    constructor(props) {
      super(props);
      this.state = {
            
      }
      console.log(this.props.lstate)
    }
   
    render(){
      return(
            <>

            </>
      )
    }
   
    gowhere(){
      this.props.navigate('/login/new');
    }
}



export default withNavigation(CssModelTest);





部分参考链接:https://blog.csdn.net/qq_42753705/article/details/121998895
页: [1]
查看完整版本: React 路由传参 三种