componentWillReceiveProps(nextProps){
在改鈎子函數里接受組件變化的最近的傳遞的props
如果在這里沒有使用nextprops 而是調用this.props
會出現一個路由切換點擊兩次的bug 會導致組件切換不及時。
}
解決辦法: 必須使用nextprops來作為參數傳值。
withRouter (react編程式導航的寫法,使用該方法后就可以讓該組件默認時具有props等屬性)
引入withRouter之后,就可以使用編程式導航進行點擊跳轉, 需要注意的是export default的暴露如上面所寫,如果結合redux使用,則暴露方式為: withRouter(connect(...)(MyComponent))
調用history的goBack方法會返回上一歷史記錄
調用history的push方法會跳轉到目標頁,如上面goDetail方法
跳轉傳參: push()可以接收一個對象參數,跳轉之后,通過this.props.location.state接收
import {withRouter} from 'react-router-dom'; goBack(){ this.props.history.goBack(); } goDetail(){ this.props.history.push('/detail'); } goDetailWithParam(item){ this.props.history.push({pathname : '/cart',state:{item}}); } <span className="ico" onClick={this.goBack.bind(this)}> <i className="iconfont"></i> </span> //這里的item來自for循環的每一項 <li onClick={this.goDetailWithParam.bind(this,item)} key={encodeURI(item.imgUrl)}> export default withRouter(Header);