Проблема при реализации вложенной маршрутизации в Reactjs - PullRequest
0 голосов
/ 09 июля 2020

Я знаю, что существует слишком много похожих вопросов, и я пробовал их, но ни один из них не устранил мою проблему. Структура моих маршрутов такая:

Layout
  /Settings Route
     UserSettings [Container]
        UserSettings [Component]
  /Private Route x
  /Private Route y
  /Private Route z
  /Private Route a

У меня есть макет, который состоит из всех частных маршрутов. Один из маршрутов - это маршрут настроек. Я хочу, чтобы мои маршруты настроек выглядели как страница настроек facebook, т. Е. Имели боковую панель с разными ссылками, которые открываются в качестве дополнительных маршрутов настроек, например:

localhost:3000/settings/**settings1**
localhost:3000/settings/**settings2**
localhost:3000/settings/**settings3**
localhost:3000/settings/**settings4**

Где settings1-2-3-4 подмаршрут и изменения. Я попытался разместить боковые панели и ссылки с NavLinks в UserSettings [component]

<Route path={`${path}/:id`} component={UserSettings[Component]} />

Ссылки при нажатии go на указанный URL-адрес, т.е. localhost: 3000 / settings / profile, но страница просто пуста.

ПРИМЕЧАНИЕ. Ссылки и боковая панель отображаются в localhost: 3000 / settings /

Но это не работает. Подскажите, пожалуйста, как это сделать, я перепробовал все имеющиеся методы.

Мой код:

//Layout.js


 //secured routes
      const PrivateRoutes = ({ component, path, isUserLogged }) => {
          return isUserLogged ? (
              <Route
                  exact
                  path={path}
                  render={() => <Suspense fallback={<Spinner />}>{component}</Suspense>}
              />
          ) : (
              <Redirect exact to="/auth" />
          );
      };
        <Switch>
            <PrivateRoutes
                path="/user"
                component={<UserProfiles />}
                isUserLogged={this.props.isUserLogged}
            />
            <PrivateRoutes
                path="/settings/"
                component={<UserSettings />}
                isUserLogged={this.props.isUserLogged}
            />

            <PrivateRoutes
                path="/"
                component={<Posts showMoreOptions={this.showPopupOptionsHandler} />}
                isUserLogged={this.props.isUserLogged}
            />
        </Switch>

// UserSettings.js [Компонент]

const EditProfileBasicInfo = (props) => {
    const [files, setFiles] = useState([]);

    return (
        <div className={style.userData}>
            <h3>Your Details</h3>

            <FilePond
                className={style.Filepond}
                allowMultiple={false}
                onupdatefiles={(fileItems) => {
                    setFiles({ files: fileItems.map((fileItem) => fileItem.file) });
                }}
                imagePreviewHeight={50}
                imageCropAspectRatio="1:1"
                // imageResizeTargetWidth={200}
                imageResizeTargetHeight={100}
                stylePanelLayout="compact circle"
                styleLoadIndicatorPosition="top center"
                // styleButtonRemoveItemPosition="center bottom"
                maxFiles={1}
                allowImagePreview={true}
                server="./"
            />

            <form onSubmit={props.submit}>
                <div className={style.Inline}>
                    <input
                        type="text"
                        placeholder="First Name"
                        id="firstName"
                        value={props.info.firstName}
                        onChange={(event) => props.changed(event)}
                    />
                    <input
                        type="text"
                        id="lastName"
                        placeholder="Last Name"
                        value={props.info.lastName}
                        onChange={(event) => props.changed(event)}
                    />
                </div>

                <textarea
                    placeholder="Bio"
                    rows="4"
                    id="bio"
                    value={props.info.bio}
                    onChange={(event) => props.changed(event)}
                />

                <input
                    type="Email"
                    id="email"
                    placeholder="Email"
                    value={props.info.email}
                    disabled
                />

                <button onClick={props.submit}>Save</button>
            </form>
        </div>
    );
};

const SidebarLinks = ({ url, to, name }) => {
    return (
        <NavLink exact to={`${url}${to}`}>
            <li>
                <button>{name}</button>
            </li>
        </NavLink>
    );
};

const UserData = (props) => {
    console.log(props);
    const currentUrl = props.match.url;
    return (
        <Grid container direction="row" className={style.UserData_MainWrapper}>
            <Grid item xs={2}>
                <ul className={style.OptionButtons}>
                    <SidebarLinks to="profile" name="Profile" url={currentUrl} />
                    <SidebarLinks to="privacy" name="Privacy" url={currentUrl} />
                    <SidebarLinks to="security" name="Security" />
                    <SidebarLinks to="logout" name="Logout" />
                </ul>
            </Grid>

            <Grid xs={10} item>
                <Route
                    to={`${props.match.url}/:settingType`}
                    render={() => <EditProfileBasicInfo {...props} />}
                />
            </Grid>
        </Grid>
    );
};

// UserSettings. js [Container] -> UserData - это в основном компоненты UserSettings // Я должен переименовать его позже.

const info = {
            email: emailVal,
            firstName: firstName,
            lastName: lastName,
            bio: bio,
        }

        return (
            <div className={style.CompleteUserData_MainWrapper}>
                <UserData
                    submit={this.onSubmitHandler}
                    info={info}
                    changed={this.onChangeHandeler}
                />
            </div>
        )

1 Ответ

0 голосов
/ 10 июля 2020

Исправил, убрав точную проп из настроек Private Route

    //Layout.js


 //secured routes
      const PrivateRoutes = ({ component, path, isUserLogged }) => {
          return isUserLogged ? (
              <Route
                 // exact   ---> This one. It stopped my routes from being displayed
                  path={path}
                  render={() => <Suspense fallback={<Spinner />}>{component}</Suspense>}
              />
          ) : (
              <Redirect exact to="/auth" />
          );
      };

---

And changing the below code:

    const SidebarLinks = ({ url, to, name }) => {
    return (
        <NavLink exact to={`${url}${to}`}>
            <li>
                <button>{name}</button>
            </li>
        </NavLink>
    );
};

const UserData = (props) => {
    console.log(props);
    const {path, url} = useRouteMatch(); ----> //import use route match
    return (
        <Grid container direction="row" className={style.UserData_MainWrapper}>
            <Grid item xs={2}>
                <ul className={style.OptionButtons}>
                    <SidebarLinks to="/profile" name="Profile" url={url} />  //Here
                    <SidebarLinks to="/privacy" name="Privacy" url={url} />  //Here
                    <SidebarLinks to="/security" name="Security" />
                    <SidebarLinks to="/logout" name="Logout" />
                </ul>
            </Grid>

            <Grid xs={10} item>
               <Switch>
               <Route path={path} exact />
                <Route
                    to={`${path}/profile`}
                    render={() => <EditProfileBasicInfo {...props} />}
                /> 
              </Switch>
            </Grid>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...