【问题标题】:React router history.push is not adding path from root?React router history.push 没有从根目录添加路径?
【发布时间】:2021-03-29 01:34:41
【问题描述】:

我的 react 应用程序中有一个自动完成输入字段,根据用户选择 react-router 将重定向到产品详细信息页面。

我的产品详情页面路径结构如下:

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

在我的自动完成功能中,我有一个 onChange 函数会触发重定向。

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

虽然这在用户位于基本 URL 路径 '/' 时有效,但如果用户尝试使用 ProductDetailContainer 中的自动完成字段,由于路径已再次添加到当前路径的顶部,它将失败,它然后会变成这样的路径'/:PrevCategory/:NewCategory/:id'

我尝试使用replace,但它似乎做同样的事情。那么有没有办法在 push() 之前将历史重置为基本 url?

#编辑 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;

【问题讨论】:

  • 你如何获得你的历史对象?
  • const history = useHistory();如果那是你要问的。我按照反应路由器站点reactrouter.com/web/api/Hooks/usehistory 的说明进行操作
  • 也希望看到您的组件与 JSX,。编辑问题以包括两者:)
  • 嗯,太好了。让我看看发生了什么事。希望我的朋友最好:)
  • 当然,添加了组件。

标签: javascript reactjs react-router-dom


【解决方案1】:

你在推的时候错过了基础/..如果你没有基础/,我会继续追加。

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

【讨论】:

  • 哦,哇,我不敢相信我错过了这一部分。感谢您的帮助!
  • 很高兴我能帮助你:)请不要忘记投票:)
猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 2019-09-05
  • 2016-10-20
  • 2019-05-30
  • 2019-11-19
  • 1970-01-01
  • 2016-01-12
  • 2020-08-16
相关资源
最近更新 更多