javascript - react-router 子頁面之間的資料傳遞
大家讲道理
大家讲道理 2017-05-19 10:40:04
0
4
973

子頁面傳遞該如何通訊?

import { HashRouter as Router, Route,  Link } from 'react-router-dom'

class Index extends Component {
  render() {
    return (
      <Router basename="/index">
        <p className="index-content" >
          <Link to="/library">library</Link>
          <Link to="/passbook">passbook</Link>
          <Link to="/login">login</Link>
          
          <br/>
          
          <Route path="/library" component={Library}/>
          <Route exact path="/passbook" component={Passbook}/>
          <Route path="/login" component={Login}/>
        </p>
      </Router>
    )
  }
}

export default Index;

1.login頁面(#/index/login)使用this.state.isLogin標識登陸狀態,進行登陸後this.state.isLogin變為true

2.這時候我切過去passbook頁面(#/index/passbook)需要login頁面(#/index/login)的isLogin來進行判斷該渲染什麼UI元件,請問一下這裡怎麼才能把login頁面的isLogin傳過去passbook頁面呢?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(4)
大家讲道理

react-router传递参数无非通过url里面的动态匹配或者query來進行傳遞,這個文檔中都很清楚。

但在這種登入態的場景中,更好的做法不是透過cookie来进行登录态的确定,从而使域名下的任何一个网页都能知道已经登录,而不需要像这样传递state

某草草

兩種方式:
第一種:透過類似redux思想,把狀態放入一個狀態機,隨用隨取,
第二種:使用history傳遞(路由跳轉),假如從路由A跳到路由B,路由B元件想取得從路由A的資料。可以這樣做:

   class A extends React.Component{
      constructor(){ super(); }
      handleClick(){
          browserHistory.push({
             state:state //传递方式1 你需要传递的状态
             query:query  //传递方式2  显示在路由路径当中的query串,路由B也可以接收;      
         })
      }
     render …………
   }
   
   class B extends React.Component{
      constructor(){
          super();
      }
      componentWillMount(){
          //当前传递过来的状态
          console.log(this.props.location.state)
      }
      render…………
  }

自己印出路由元件的 this.props 看一下,裡面有很多你需要的東西。

洪涛

使用 redux/flux, 儲存登入狀態
並且使用 cookie/LocalStorage/SessionStorage, 儲存使用者登入後的資訊,
否則 刷新頁面之後,還是未登入狀態

PHPzhong

可以使用react-redux去把相關需要的參數存放在store上面,然後connect每一個子元件,store的參數就可以當作props來使用了

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板