鍍金池/ 問答/C  Linux  HTML/ react路由Link標簽點擊時候路由不變,重新渲染組件

react路由Link標簽點擊時候路由不變,重新渲染組件

網站左側導航中點擊link跳轉路由,在一個路由中不同的操作會寫渲染不同的組件,想在重新點擊左側導航時重新渲染為最初的組件,該如何做;

<Link to="/a">個人資料</a>
組件a中不同的操作,會根據判斷渲染不同的組件,我在渲染到第二個組件的時候,用戶重新點擊左側導航想從新走生命周期渲染默認的第一個組件
回答
編輯回答
絯孑氣

使用react-router的createElement解決!
Router.js

......
...... // 省略其他無關緊要代碼

// 此處為要點擊刷新的組件
const arr = [
    home
];

// 開關優(yōu)化
let onOff =false;

// 頁面強制刷新,如果需要強制刷新在路由中添加onChange事件以及在組件數組添加
const createElement=(component, props) =>{
    if (props.children && onOff || props.children && arr.includes(props.routes.slice(-1)[0].getComponent)) {
        let children = Object.assign({}, props.children, {key : `${window.location.pathname}` + new Date().getTime()})
        props = { ...props, children };
        onOff = false;
    }
    return React.createElement(component, props)
}

const onChange = (props, next) => {
    onOff = true
    console.log(`${next.location.pathname}`, 'change');
}

const RouteConfig = (
    <Router history={history} createElement = {createElement}>
        <Route path="/home" getComponent={home} onChange = {onChange} />
        ...
        ...
    </Router>
);

export default RouteConfig;

如果您用的react-router4.0,當使用 component 時,router 將使用 React.createElement 根據給定的 component 創(chuàng)建一個新的 React 元素。這意味著如果你使用內聯函數(inline function)傳值給 component將會產生不必要的重復裝載。對于內聯渲染(inline rendering), 建議使用 renderprop。
也可以參考下我新寫的文章:這里有沒有你想要的react-router

2018年3月5日 01:14
編輯回答
刮刮樂

給路由url上加個參數,可以加在url params也可以是query里

2018年2月19日 00:26