【问题标题】:react-router-dom v5 - Link works, but Redirect and history.push() do notreact-router-dom v5 - 链接有效,但 Redirect 和 history.push() 无效
【发布时间】:2021-07-19 09:07:19
【问题描述】:

编辑:我很尴尬地说,答案是我发送给重定向和历史记录.push() 的 URL 中的拼写错误。所以对于任何想知道的人来说,似乎 Link、Redirect 和 history.push() 应该是一样的。


为什么 Link 可以完全工作,而 Redirect 和 history.push() 只更新 URL 而不会在该 URL 处呈现组件?

我想做以下事情:

  • 用户单击一个按钮,该按钮通过 Redux 操作创建器调用服务器端函数
  • 服务器函数将数据写入 Firebase Firestore
  • 服务器函数返回文档ID,操作创建者使用该ID来history.push()在前端显示新文档的具体URL。

这会在浏览器中生成正确的 URL,但不会呈现它应该呈现的组件。我测试了对同一个 URL 的重定向和链接进行硬编码,只有链接可以完全工作。

我尝试过的:

  • 使用 BrowserRouter、Router 和 HashRouter
  • 将选择的路由器放在 App 组件的外部和内部
  • 使用 useHistory() 访问历史记录并将历史记录从我的组件传递给操作创建者
  • 使用历史配置文件,将其作为组件传递给路由器,并将其导入到动作创建者文件中

index.js 文件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import { Router } from 'react-router-dom'

import history from './config/history'

// firebase and store config ommitted

ReactDOM.render(
  <Provider store={store}>
    <ReactReduxFirebaseProvider {...rrfProps}>
      <Router history={history} >
        <App />
      </Router>
    </ReactReduxFirebaseProvider>
  </Provider>,
  document.getElementById('root')
);

history.js

import { createBrowserHistory } from 'history'
const history = createBrowserHistory()
export default history;

动作创建者

import history from '../../config/history'

export const importWebsite = (data) => {
  return (dispatch, getState, { getFirebase }) => {
    const firebase = getFirebase()
    const profile = getState().firebase.profile
    const userId = getState().firebase.auth.uid

    data = {
      ...data,
      userFirstName: profile.firstName,
      userLastName: profile.lastName,
      username: profile.username,
      userId: userId,
    }
    const pull_website = firebase.functions().httpsCallable('pull_website')
    pull_website(data)
      .then((res) => {
        dispatch({ type: 'IMPORT_SUCCESS' })
        history.push('/websites/' + res.data.id)
      }).catch((err) => {
        dispatch({ type: 'IMPORT_FAIL', err })
      })
  }
}

【问题讨论】:

    标签: reactjs react-redux react-router-dom


    【解决方案1】:

    除非有任何奇怪之处,例如将应用程序的某些部分渲染为多个 Router 组件,那么我认为这里的问题是您的路由上下文在 redux 提供程序内部,或者换句话说,没有 Router 或路由上下文高于 ReactTree 中的 redux 提供程序(和异步操作中间件)。

    解决方案:将Router 包裹在Provider 周围。

    ReactDOM.render(
      <Router history={history} >
        <Provider store={store}>
          <ReactReduxFirebaseProvider {...rrfProps}>
            <App />
          </ReactReduxFirebaseProvider>
        </Provider>
      </Router>,
      document.getElementById('root')
    );
    

    【讨论】:

    • 谢谢 - 令人尴尬的是,我的解决方案只是一个错字,但我还是实现了这个,以防它防止任何其他奇怪的行为。
    • @bront 不用担心......我们都会偶尔犯错。祝你好运!
    猜你喜欢
    • 2019-04-21
    • 2021-06-19
    • 2019-02-09
    • 2021-02-01
    • 2020-06-03
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多