【问题标题】:How to re-load page on redirect React如何在重定向 React 上重新加载页面
【发布时间】:2020-03-12 17:51:44
【问题描述】:

在我的应用程序中,我使用 React Router 向我的应用程序添加路由。一旦用户单击保存,我将使用 withRouter history 从我的 AddAlbum 类组件重定向到我的主页(提要)页面。我的问题是我的 AddAlbum 组件正在更新我的主页,因此我需要在重定向后重新加载我的主页以查看我的 AddAlbum 组件所做的更改。我将如何做到这一点?

这是我的路由在我的 App.js 组件中的样子:

import { BrowserRouter, Router, Route } from "react-router-dom";
return (
    <BrowserRouter>
      <div className="App">
      <Router history={history}>
      <Route path="/album/create" component={AddAlbum}/>
      <Route exact path="/feed" component={Feed}/>
      </Router>
      </div>
    </BrowserRouter>
  );

AddAlbum 和 home(Feed) 都是类组件。

在我的 AddAlbum 组件中,我在 onClick 方法中使用 withRouterhistory 进行重定向。这是按钮的完整功能(重定向到最后一个.then():)

this.onClick = this.onClick.bind(this);
this.save2 = this.save2.bind(this);

save2(event) {
  event.preventDefault();
  let user_id;
  let image;
  let data;
  const { history } = this.props;

  Promise.resolve().then(()=>{
      user_id = this.context.user.sub;
      image = this.state.file;
      data = new FormData()
      data.append('file', this.state.file)
  }).then(()=> { 
      this.setState(prevState => ({
      files: prevState.files.map((file, index) => ({...file, index})
  )}));

  let files = this.state.files;
   this.setState(prevState => ({
   albums: {...prevState.albums, files, user_id}
}))

   Array.from(this.state.songsList).forEach(song => {
    data.append('songs', song)
  })

  data.append('albums', JSON.stringify(this.state.albums))


}).then(()=> {
    axios.post("http://localhost:3000/albums", data, { 
  }).then(res => { // then print response status
    console.log(res.statusText)
 })
})
.then(()=> {
  const { match, location, history } = this.props;
  history.push('/feed');
})
.catch((err)=> {console.log(err)});

}

onClick(event) {
  let albums = this.state.albums;
  if(albums.date  === "" || albums.title  === "" || albums.description === "") {
    alert("ERROR: Fields Must Be Filled In Before You Save");
    } else {
  this.save2(event);
  }
}

render() {
    return(
        <ButtonToggle onClick={this.onClick} color="success">
            Save
        </ButtonToggle> 
    )
}

重定向到主页(Feed)组件后,如何重新加载它?

【问题讨论】:

  • 你在使用某种全局状态吗?因为在每次路由更改时,您的组件都应该再次渲染。没有任何旧值。
  • @JeanAguilar 全局状态是什么意思,在哪里?如果我单击带有 React Router 的链接,我认为它不应该重新加载。不知道我是否使用 withRouter 进行重定向。
  • 重定向工作正常,对吧?
  • 是的,重定向工作正常
  • 请添加更多 AddAlbum 组件的代码。特别是保存按钮部分。

标签: javascript reactjs


【解决方案1】:

问题: 在您的axios.post 之后(catch 之前的 9 行),您不会更新您的状态。这就是您看不到更改的原因。

解决方案 1:如果 POST 请求正确返回,请更新您的状态(将相册添加到相册的数组中)。

解决方案 2:如果 POST 请求正确返回,请使用 window.location.reload() 重新加载您的页面,这样您的相册就会从 apicall 更新。像这样的:

    axios.post(yourURL, yourData)
        .then(res => {
            // check if response is correct and
            window.location.reload();
        })
        .catch(console.error);

希望对你有帮助。

【讨论】:

  • 如果我在我的 home(Feed) 组件中添加具有与 componentDidMount() 相同的 setState 的 componentDidUpdate,我的组件会在页面上获取新数据。唯一的问题是我收到一条警告:Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
  • 我在这里问了这个问题:stackoverflow.com/questions/60661197/…
  • 这看起来像是一个不同的问题:相册似乎处于 Feed 状态,并且 Feed 已卸载。您可以将该 var 置于某个父状态,或者更简单地说,使用解决方案 2 并执行 window.location.reload()
【解决方案2】:

我刚刚对您的代码进行了快速扫描,但我认为问题出在您的 axios 发布请求中。这样,当您重定向到 /feed 时,它将从该端点提取更新的数据。

axios.post("http://localhost:3000/albums", data, {})
  .then(res => {
      // then print response status
      console.log(res.statusText);

      // redirect only when your http request is complete.
      history.push("/feed");
  });

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2021-06-29
    • 1970-01-01
    • 2021-10-25
    • 2022-12-11
    • 2021-07-18
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多