【问题标题】:react router dom, replaces the browser url but does not go to the pagereact router dom,替换浏览器url但不去页面
【发布时间】:2020-03-31 01:01:23
【问题描述】:

非常感谢您

我正在尝试访问 Drawer 组件的子页面,但是当我尝试使用 hisotry.push ('route name') 时,它只是在 url 中替换它但不导航到链接,我通过历史使用导航服务我不知道干扰和组件是否是抽屉的孩子,但它具有相同的地址。 档案传奇

src/service/routes.js

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export default history;

src/modules/sagas.js

function* detailsUsers({ payload: { user } }) {
  yield put(defineInformationDetails(user));
  history.push(`Drawer/EditAdm`);
}

src/router/index.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';

import Login from '../pages/Login';
// import Panel from '../pages/Panel';
import Panel from './Drawer';
import * as isUserLogged from '../store/modules/auth/actions';
import ResetPassword from '../pages/ResetPassword';
import ChangePassword from '../pages/ChangePassword';

export default function Routes() {
  return (
    <Switch>
      <Route path="/" exact component={Login} />
      <Route path="/Login" component={Login} />
      <Route path="/ResetPassword" component={ResetPassword} />
      <Route path="/ChangePassword" component={ChangePassword} />
      <Route path="/Drawer" component={Panel} />
    </Switch>
  );
}

src/routes/drawer.js

 const [drawer, setDrawer] = useState({
    name: 'Menu',
    subname: '',
    options: [
      {
        id: '1',
        name: 'Home',
        open: true,
        link: `/`,
        icon: () => <IconHome />,
        route: {
          path: `${path}/`,
          exact: true,
          main: () => <Home />,
        },
        suboptions: [],
      },
      {
        id: '2',
        name: 'Cadastro de Usuário',
        open: false,
        link: false,
        icon: () => <IconUserList />,
        route: null,
        suboptions: [
          {
            id: '1',
            name: 'Buscar/Editar Usuário',
            open: false,
            link: `/SearchUser`,
            icon: () => <IconSearchFa />,
            route: {
              path: `${path}/SearchUser`,
              exact: true,
              main: () => <EditUser />,
            },
          },
          {
            id: '2',
            name: 'Administrador',
            open: false,
            link: `/AdmRegistration`,
            icon: () => <IconRegisters />,
            route: {
              path: `${path}/AdmRegistration`,
              exact: true,
              main: () => <AdmRegistrator />,
            },
          },
          {
            id: '5',
            name: 'Fornecedor',
            open: false,
            link: `/SupplierRegistrator`,
            icon: () => <IconRegisters />,
            route: {
              path: `${path}/SupplierRegistrator`,
              exact: true,
              main: () => <SuppliedRegistrator />,
            },
          },
          {
            id: '6',
            name: 'Controle de acesso nos eventos',
            open: false,
            link: `/EventAcess`,
            icon: () => <IconEvent />,
            route: {
              path: `${path}/EventAcess`,
              exact: true,
              main: () => <EventAcess />,
            },
          },
          {
            id: '7',
            name: 'Editar Administrador',
            open: false,
            link: `/EditAdm`,
            icon: () => {},
            route: {
              path: `${path}/EditAdm`,
              exact: true,
              main: () => <EditAdm />,
            },
          },
        ],
      },
    ],
  });
  return (
    <Router>
      <AreaPanel>
        <Header
          name={
            localStorage.getItem('NeoTicket@name') !== null
              ? localStorage
                  .getItem('NeoTicket@name')
                  .substring(0, 1)
                  .toUpperCase()
                  .concat(localStorage.getItem('NeoTicket@name').substring(1))
              : 'Nome Usuário'
          }
          functionOnClickDrawer={() => setOpenDrawer(!openDrawer)}
          openDrawer={openDrawer}
          functionOnClickUser={() => setOpenUser(!openUser)}
          openUser={openUser}
        />
        <AreaDrawerPanel>
          <AreaDrawer open={openDrawer}>
            <Drawer
              name={drawer.name}
              subname={drawer.subname}
              openDrawer={openDrawer}
              options={drawerSearch.options}
              functionOnClickOpenSuboption={id =>
                functionOpenSuboption(id, drawerSearch)
              }
              functionSearchText={text => setSearchText(text)}
              functionOnClickName={name => functionGetNamePage(name)}
              path={path}
            />
          </AreaDrawer>

          <AreaContent open={openDrawer}>
            <HeaderContainer>
              {/* {drawer.options.map((option, index) => {
                const { link } = option;
                if (link) {
                  return (
                    <HeaderContent
                      key={index.toString()}
                      name={namePage === '' ? 'TESTE' : namePage}
                    />
                  );
                }
              })} */}

              <Switch>
                {drawer.options.map((option, index) => {
                  const { link, route, suboptions } = option;
                  if (link) {
                    return (
                      <Route
                        key={index.toString()}
                        path={route.path}
                        exact={route.exact}
                        children={<route.main />}
                      />
                    );
                  }
                  return suboptions.map((suboptions, indexParam) => {
                    return (
                      <Route
                        key={indexParam.toString()}
                        path={suboptions.route.path}
                        exact={suboptions.route.exact}
                        children={<suboptions.route.main />}
                      />
                    );
                  });
                })}
              </Switch>
            </HeaderContainer>
          </AreaContent>
        </AreaDrawerPanel>
      </AreaPanel>
    </Router>

我不明白怎么解决。

【问题讨论】:

  • 当您在Switch 中开发路由组件时,您希望将最具体的路由放在列表顶部。
  • @Daniel 我不明白你的意思,可以写其他吗?
  • 您想将Route path="/" 放在列表的最后,因为它是最不具体的路线。
  • @Daniel,可能是这样,但这对解决问题有什么帮助?

标签: reactjs react-router


【解决方案1】:

在文件 sagas 中替换。

history.push(`Drawer/EditAdm`)

const { pathname } = history.location;
window.location.href = `${pathname}/EditAdm`;

【讨论】:

  • 使用windwos.location.href时,它会更新我的数据reducer并且页面没有检索到数据
【解决方案2】:

可能的解决方案: 将组件与 withRouter 一起使用 \src\pages\UserRegister\index.js

import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { Container } from './styles';
import * as HomeActions from '../../store/modules/home/actions';
import Button from '../../components/ButtonIcon';

function UserRegistration({ history }) {
  const dispatch = useDispatch();
  function onChangePageChildren() {
    dispatch(HomeActions.changePageChildren(history));
  }
  return (
    <Container>
      <a>Tela1</a>
      <Button
        title="chamar sagas para ir para tela de listagem"
        functionOnClick={() => onChangePageChildren()}
      />
    </Container>
  );
}
export default withRouter(UserRegistration);

但是,这样他将保留导航属性以供使用,因此您可以获取历史属性并将其作为参数传递给操作并通过 sagas 传递。 传奇文件

import { all, call, put, takeLatest } from 'redux-saga/effects';
import { createBrowserHistory } from 'history';
import {
  loading,
  successAction,
  failureAction,
  breakAction,
} from '../common/actions';

function* requestChangePage({ payload: { history } }) {
  yield put(loading(''));
  history.push('/Drawer/userList');possível resolução:
abrace o componente com withRouter
\src\pages\UserRegister\index.js

值得一提的是,在这种情况下,当始终在带有标题的页面上使用抽屉并要求在一个区域中进行分页时,这些被定义为该组件抽屉的子级,现在这可行,但我相信最好的方法。 请记住,这种方式不会影响页面缩减器的状态。

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 2020-07-02
    • 1970-01-01
    • 2022-11-23
    • 2020-09-01
    • 2022-07-28
    • 2018-12-26
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多