天天看點

在普通 js檔案中,需要使用 history, 遇到的兩個坑!!!

1. 在 安裝 react-router-dom 的時候,自帶安裝 history 包,直接 import 即可

history:object

1.1 起因:

在看文檔的時候,看到 demo 中 import 了 history 包。于是乎,我就先去 yarn add history 。 沒想到,在點選頁面的時候,頁面先是空白的,必須手動重新整理,才會出現正常的目前頁面内容。

1.2 處理:

  • yarn remove react-router-dom
  • yarn add react-router-dom

1.3 code

// history.js 
import { createBrowserHistory } from "history";
export default createBrowserHistory();
           
// index.js 
import { Router, Route, Switch, Redirect } from "react-router-dom";
import history from "@/utils/history";


function App() {
  return (
    <Router history={history}>
    </Router>
)}
           

2. history.push() 中,可以傳遞兩種方式的值

2.1 history.push(path, [state])

history-is-mutable

  • 在文檔中, 顯示 history.push(path, [state]) - (function) Pushes a new entry onto the history stack
history.push("/login", { from: history.location });  // 後面的對象,就是 **state**
           

2.2 history.push({ pathname: ‘’,search: ‘’,state: { }})

<Router history={history}>
      <div className="App">
        <Suspense fallback={<div>...loading</div>}>
          <Switch>
            <Redirect exact from="/" to="/home" />
            <Route path="/home" component={Layout} />
            <Route path="/login" component={Login} />

            <AuthRoute path="/profile/edit" component={EditProfile} />
            <AuthRoute path="/profile/chat" component={EditChat} />
          </Switch>
        </Suspense>
      </div>
    </Router>
           
  • 解釋: 每一個元件,都可以通過 render-props 的傳值方式,去傳值 或者 接收值

    比如:

stackoverflow

// navigate 到 template 頁面
this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})
           
// similarly for the Link component or the Redirect component
<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>
           

2.3 通過 useLocation() 可以取值

const location = useLocation();


let { from } = location.state || { from: { pathname: "/home" } };
      history.replace(from);

           

繼續閱讀