简体   繁体   English

React router history.push 没有从根目录添加路径?

[英]React router history.push is not adding path from root?

I have a autocomplete input field in my react app, base on the user selection react-router will redirect to the product detail page.我的反应应用程序中有一个自动完成输入字段,基于用户选择 react-router 将重定向到产品详细信息页面。

My product detail page path is structured as below:我的产品详细信息页面路径结构如下:

<Route extact path={'/:category/:id'} component={ProductDetailContainer}/>

In my autocomplete, I have an onChange function that will trigger the redirect.在我的自动完成中,我有一个onChange function 将触发重定向。

const handleChange(event, value) => {
   history.push(`${value.category}/${value.id}`) 
}

While this works when the user is in base URL path '/' , it will fail if the user attempt to use the autocomplete field in ProductDetailContainer due to the path has been added on top of the current path again, it will then become a path like this '/:PrevCategory/:NewCategory/:id'虽然这在用户位于基本 URL 路径'/'时有效,但如果用户尝试使用ProductDetailContainer中的自动完成字段,由于路径已再次添加到当前路径之上,它将失败,然后它将成为路径像这样'/:PrevCategory/:NewCategory/:id'

I tried to use replace but it seems to do the same thing.我尝试使用replace ,但它似乎做同样的事情。 So is there a way to reset history to base url before push()?那么有没有办法在push()之前将历史重置为基础url?

#Edit 1 This is where the to autocomplete field and history are a push. #Edit 1 这是自动完成字段和历史记录的推动力。

import React from 'react';
import { useHistory } from "react-router-dom"

import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import { fade, makeStyles } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';

import TextField from '@material-ui/core/TextField'
import CircularProgress from '@material-ui/core/CircularProgress'
import Autocomplete from '@material-ui/lab/Autocomplete'

const useStyles = makeStyles((theme) => ({
....
}));

const TitleBar = () => {
  const classes = useStyles();
  const history = useHistory();
  const [open, setOpen] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const loading = open && options.length === 0;

  React.useEffect(() => {
    let active = true;

    if (!loading) {
      return undefined
    }

    (async () => {
      const response = await fetch(site)

      const products = await response.json();
      
      if (active){
        setOptions(products)
      }

    })();

    return () => {
      active = false;
    };

  }, [loading])

  React.useEffect(() => {
    if (!open) {
      setOptions([]);
    }
  }, [open])

  const handleChange = (event, value) => {
    if (value !== null) {
      // redirect to product detail page if user selected an item
      history.replace(`${value.category}/${value.id}`)
    }
  }

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            edge="start"
            className={classes.menuButton}
            color="inherit"
            aria-label="open drawer"
          >
            <MenuIcon />
          </IconButton>

          <div className={classes.search}>

            <Autocomplete
              id='aysncSearchBar'
              style={{ width : 300}}
              open={open}
              onOpen={()=>{setOpen(true)}}
              onClose={()=>{setOpen(false)}}
              getOptionSelected={(option, value) => option.id = value.id}
              getOptionLabel={(option) => option.title}
              options={options.sort((a,b) => -b.category.localeCompare(a.category))}
              groupBy={(option) => option.category}
              loading={loading}
              onChange={handleChange}
              renderInput={(params) => (
                <TextField 
                  {...params}
                  label="Search"  
                  variant="outlined"
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <React.Fragment>
                        {loading ? <CircularProgress color="inherit" size={20} /> : null}
                        {params.InputProps.endAdornment}
                      </React.Fragment>
                    ),
                  }}
                />
              )}

            />
          </div>

        </Toolbar>
      </AppBar>
    </div>
  );
}

export default TitleBar;

You are missing the base / while pushing.. if you do not have base / , il will keep appending.您在推时缺少基础/ ..如果您没有基础/ ,我将继续追加。

history.push(`/${value.category}/${value.id}`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM