useHistory-无法读取未定义的属性“ push”

时间:2020-11-05 16:17:39

标签: javascript reactjs react-router-dom

按下主页按钮后,我要将其重定向到主页“ /”。但我收到此错误。我能做什么 ? :

import { Route, useHistory } from 'react-router-dom/cjs/react-router-dom.min';
const history = useHistory();

const homeButtonOnClickHandler = () =>{
    history.push("/");
}
  
<Router>
    <Header homeButtonOnClickHandler={homeButtonOnClickHandler}/>
    <Switch>
        <Route path='/result'>
            <Result
                ingredients={ingredients}
                total={() => hesapla()} 
            />
        </Route>

        <Route path='/'>
            <Home
                ingredients={ingredients} 
                total={() => calculate()} 
                ingredientAdd={(i) => ingredientAdd(i)}
                ingredientRemove={(i) => ingredientRemove(i)}
                selectedIngredients={ingredients}
                isOrder={number}
            />
        </Route>
    </Switch>
</Router>

2 个答案:

答案 0 :(得分:1)

您只需要将钩子和处理程序放入组件中即可,例如:link

答案 1 :(得分:1)

您正在尝试在history之外使用Router钩子。在Header组件中编写函数。

Header组件内部尝试

const history = useHistory();

const homeButtonOnClickHandler = () =>{
            history.push('/');
}