【问题标题】:after using react-router-dom, the url has changed, but page didn't re-render使用 react-router-dom 后,url 发生了变化,但页面没有重新渲染
【发布时间】:2021-01-27 12:48:02
【问题描述】:

我正在为我的项目使用 react、redux、react-router,但我遇到了一个问题。

每当我使用 history.push()Link to='' 时,目标网站都不会呈现,但刷新后,一切似乎又正常了!

(将 {forcefresh: true} 添加到 ./history 似乎可以解决问题,但还有其他方法可以解决问题!)

如你所见,isSignedIn 在重定向后为空:

但是刷新后会得到true的值。

我的减速机:

import { SIGNED_IN, SIGNED_OUT } from '../actions/actionTypes';

const initialState = {
  isSignedIn: null,
  userInfo: null,
};

export default (state = initialState, action) => {
  switch (action.type) {
    case SIGNED_IN:
      return { ...state, isSignedIn: true, userInfo: action.payload }; //important parts!
    case SIGNED_OUT:
      return { ...state, isSignedIn: false, userId: null };
    default:
      // return { ...state, isSignedIn: true, userInfo: action.payload };
      return initialState;
  }
};

【问题讨论】:

  • /client/src/components/App/App.js 用于路由器和路由设置
  • /client/scr/history.js 用于历史设置
  • 您应该已经在问题本身中发布了代码。但是您的路由器设置看起来不错。确切的问题是什么?您是否无法使用history.push 转到任何路线,或者是身份验证问题,即登录完成后您看不到主页/仪表板页面?
  • 我在这里有视频格式的详细问题:kapwi.ng/c/njymI7Aw

标签: reactjs redux react-router


【解决方案1】:

在你的减速器中,当你有一个未处理的动作时,你正在重置状态(返回初始状态):

  switch (action.type) {
    ...
    default:
      return initialState;
  }

这就是isSignedIn 在重定向后变为空的原因。因为当有一个未处理的动作时,那将重置状态。 (我查看了您的存储库,有一个名为 FETCH_COUNTS 的操作未处理。)

所以改成:

export default (state = initialState, action) => {
  switch (action.type) {
    case SIGNED_IN:
      return { ...state, isSignedIn: true, userInfo: action.payload }; //important parts!
    case SIGNED_OUT:
      return { ...state, isSignedIn: false, userId: null };
    default:
      console.error('action is not handled!', action)
      return state; // <----- just return previous state when the actiontype is not recognized
  }
  return state
};

这样当您有未处理的操作时它不会重置状态。

【讨论】:

  • 首先,非常感谢您的回答!但这里出现了另一个问题,每当我尝试创建一个新的“计数”时,在 src/components/Menucount 中它会创建两个完全相同的计数!奇怪的是,当我刷新页面时,第二个计数消失了!你能解释一下这个问题吗?为什么会这样!提前致谢!
  • @water 问题是您要添加新项目 2 次。一个当你发送 CREATE_COUNT 动作时,另一个当你发送 FETCH_COUNTS 动作时。解决方案是:在countReducers 的第30 行,删除...state,,因为它不应该添加获取的那些,它应该替换它们。
猜你喜欢
  • 2020-02-08
  • 2022-07-28
  • 2021-01-11
  • 1970-01-01
  • 2018-10-28
  • 2021-10-21
  • 2022-12-17
  • 2020-07-19
  • 2021-02-22
相关资源
最近更新 更多