【问题标题】:ReactJS: onClick `window.location.href` return previous page valueReactJS:onClick `window.location.href` 返回上一页值
【发布时间】:2020-01-03 11:55:44
【问题描述】:

在我的 react 项目中,我需要根据页面位置对 redux 操作设置条件。

所以我使用window.location.href 来获取当前页面的值,但它返回最后访问的页面值。

export const getBlog = (type, offset) => {
  console.log(window);
  console.log(window.location.pathname);
  if( window.location.pathname !== '/planner' ){
    return (dispatch) => {

        dispatch({ type: 'BLOG_LOADING_START'})

      axios.get(siteurl + TPW.CATEGORY_API + type, {
        headers: { 'Content-Type': 'application/json' } })
        .then(response => {
        let ary =  response.data.slice(0, offset)
        dispatch({
            type: 'SET_BLOG_DATA',
            list: response.data,
            blogData: ary,
            total: response.data.length,
            offSetCnt: 3
        })
        dispatch({ type: 'BLOG_LOADING_DONE'})
      });
    }
  }
}

第一张console.log(window)截图;它返回实际访问的页面位置结果。

第二个console.log(window.location.pathname) 返回之前访问过的页面值。

【问题讨论】:

    标签: reactjs react-redux react-router


    【解决方案1】:

    我相信控制台在您登录时不会对窗口进行深层复制。 它会在您展开位置节点时加载该值。

    这就解释了为什么这两个结果不同。

    【讨论】:

      【解决方案2】:

      window.location.pathname 始终为您提供您登陆的页面。由于我们使用react-router 获取当前路线,您需要使用this.props.location

      你可以参考这个答案更清楚

      get location

      【讨论】:

      猜你喜欢
      • 2019-12-20
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多