首页 > 解决方案 > history.push() 正在更新 url 但不重新渲染组件

问题描述

我遇到了 react-router-dom 的问题。我正在尝试history.push在执行操作后用于导航。但问题是createBrowserHistory from history更新 url 但组件没有重新渲染。我已经使用了https://stackoverflow.com/中的所有解决方案。但它仍然没有按预期工作。

不过我找到了背后的原因。由于我的组件是用connect函数包装的,connect因此可以防止重新渲染。还有一个解决方案,connectwithRouter. 我也试过了。但它不起作用。

这是我的 App.js

import React, { Component } from "react";
import { Router, Route } from "react-router-dom";
import history from "../history"
import Navbar from "./Navbar";
import LogIn from "./LogIn";
import StreamCreate from "./streams/StreamCreate";
import StreamDelete from "./streams/StreamDelete";
import StreamEdit from "./streams/StreamEdit";
import StreamList from "./streams/StreamList";
import StreamShow from "./streams/StreamShow";
import Profile from "./streams/Profile";

class App extends Component {
  render() {
    return (
      <div>
        <Router history={history}>
          <div>
            <Navbar />
            <Route path="/" exact component={StreamList} />
            <Route path="/streams/new" exact component={StreamCreate} />
            <Route path="/streams/delete" exact component={StreamDelete} />
            <Route path="/streams/edit" exact component={StreamEdit} />
            <Route path="/streams/show" exact component={StreamShow} />
            <Route path="/login" exact component={LogIn} />
            <Route path="/my-streams" exact component={Profile} />
          </div>
        </Router>
      </div>
    );
  }
}

export default App;

这是history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

动作创建者:

import Streams from "../API/Streams";
import history from "../history";

export const createStreams = (formData) => async (dispatch, getState) => {
  const { userId } = getState().auth;
  const response = await Streams.post("/streams", { ...formData, userId });
  dispatch({ type: "CREATE_STREAM", payload: response.data });
  history.push("/")
};

标签: reactjsreact-reduxreact-router-dombrowser-history

解决方案


推荐阅读