React Hook 之 ‘react-router’ 中 hook 使用

393 阅读1分钟

改变路由state

页面直接的传参可以通过改变 state 达到目的

image.png

传参方式(页面 A):

import { useHistory } from 'react-router';

const history = useHistory()

const handleEnter = () => {
    // state 为 需要传给页面 B 的参数
    let state = {
      name: 'sera',
      age: 12
    }
    history.replace('页面 B 路径', {...history.location.state, ...state})
}

监听 state 改变:

import React, { useEffect } from 'react';
import { useHistory, useLocation } from 'react-router';

const history = useHistory();
const { state } = useLocation()

useEffect(() => {
   console.log('页面路径已经改变了')
   console.log(state) // { name: 'sera',  age: 12 }
}, [state])