history.push()正在更新URL,但未重新呈现组件

时间:2020-07-31 11:45:23

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

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

但是我找到了背后的原因。由于我的组件是用connect包装的,因此connect阻止了重新渲染。还有一种解决方案,用connect包装withRouter函数。我也尝试过但这不起作用。

这是我的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("/")
};

0 个答案:

没有答案