简体   繁体   中英

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.

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.

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'

I tried to use replace but it seems to do the same thing. So is there a way to reset history to base url before push()?

#Edit 1 This is where the to autocomplete field and history are a push.

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}`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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