React router 的历史道具在页面加载时自行执行

History prop of react router getting executed itself on page load

我正在学习 react router@v4,在 运行我的代码中遇到了意想不到的情况。如下:

我写了下面几行以导航到另一个组件:

<NavLink to="/data">Dummy Data</NavLink>
<Route path="/data" component={DataStore} history={history} />

其中{}里面的history是一个const变量,引用了React的createBrowserHistory()。在 DataStore 页面上,我写了一个带有 onclick 功能的按钮代码,如下所示:

<button onClick={this.props.history.push("/")}>Back</button>

当我在主页上单击虚拟数据 link 时,控件重定向到 DataStore 组件,并且在完成页面加载操作后没有任何操作返回到主页。意味着为 onClick 函数指定的代码在页面加载时执行,无需单击按钮。为了克服这个问题,我在 DataStore 组件中编写了不同的函数,我在单击按钮时调用它,并在其中编写了 "this.props.history.push('/')"。然后我又 运行 我的代码,它工作正常。

任何人都可以指导我在页面加载时反应历史功能的上述异常行为。非常感谢您的帮助。

<button onClick={this.props.history.push("/")}>Back</button>

马上执行

<button onClick={()=>this.props.history.push("/")}>Back</button>

将在点击时执行