react路由Link标签点击时候路由不变,重新渲染组件

网站左侧导航中点击link跳转路由,在一个路由中不同的操作会写渲染不同的组件,想在重新点击左侧导航时重新渲染为最初的组件,该如何做;

<Link to="/a">个人资料</a>
组件a中不同的操作,会根据判断渲染不同的组件,我在渲染到第二个组件的时候,用户重新点击左侧导航想从新走生命周期渲染默认的第一个组件
阅读 9.2k
2 个回答

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

......
...... // 省略其他无关紧要代码

// 此处为要点击刷新的组件
const arr = [
    home
];

// 开关优化
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 创建一个新的 React 元素。这意味着如果你使用内联函数(inline function)传值给 component将会产生不必要的重复装载。对于内联渲染(inline rendering), 建议使用 renderprop。
也可以参考下我新写的文章:这里有没有你想要的react-router

给路由url上加个参数,可以加在url params也可以是query里

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题