通过反应路由器重新加载相同路由后的 API 调用 [英] API call after reloading same route via react router

查看:41
本文介绍了通过反应路由器重新加载相同路由后的 API 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过redirect从react-router-dom v4重新加载一个组件,当组件第一次加载时,API 调用发生在 ComponentDidMount 中.但是当组件重新加载由重定向触发时,此方法不会运行.

我有组件 TopicList ,它使用来自 react-router-dom 的 Route 由路径/topic 显示

PostTopic 是在 TopicList 中呈现的模态.在 PostTopic 内部,我向状态添加了一个名为 redirect 的属性,并使用它来将重定向组件呈现为 =/topic",我在将一些数据发布到 api 后重定向.

在通过重定向重新加载的 topicList 中,componentDidMount() 未运行,因此不会发生用于获取新发布数据的 api 调用.

通过redirect from react-router重新加载同一路由后,从api调用重新获取数据的最佳方法是什么.

class PostTopic 扩展组件状态 = {重定向:假}handleSubmit = (e) =>{e.preventDefault();const { body, subject } = this.state;api.postTopic(this.props.store.token,subject,body).then( 响应 => {this.setState({重定向:true})}).catch( 错误 => {this.setState({error});});}renderRedirect = () =>{如果(this.state.redirect){return <重定向到={this.props.currentPath}/>}}使成为(){返回(.........{this.renderRedirect()}}}

解决方案

componentDidMount 只会在组件最初安装在 DOM 中时运行,并且当 URL 参数更改时新组件不是安装.

您需要使用 componentDidUpdate 并检查 URL 参数是否已更改,如果是,则再次获取您的数据.

示例

function getData() {返回新的承诺(解决 => {setTimeout(() => {resolve(Array.from({ length: 3 }, () => Math.random()));}, 1000);});}class Page 扩展了 React.Component {状态 = { 数据:[] };componentDidMount() {getData().then(data => {this.setState({数据});});}componentDidUpdate(prevProps) {if (prevProps.match.params.pathParam !== this.props.match.params.pathParam) {getData().then(data => {this.setState({数据});});}}使成为() {返回 (<div>{this.state.data.map(element => <div key={element}>{element}</div>)}

);}}类 App 扩展了 React.Component {使成为() {返回 (<浏览器路由器><div><链接到="foo">Foo </Link><链接到=栏">栏<开关><Route path="/:pathParam" component={Page}/></开关>

</BrowserRouter>);}}

I am reloading a Component via Redirect from react-router-dom v4, When the Component loads for the first time the api calls occur within ComponentDidMount. But this method doesn't run when component reload is triggered by Redirect.

I have the component TopicList , which is displayed by the path /topic using Route from react-router-dom

PostTopic is a Modal that is rendered within TopicList. Inside PostTopic , i add a property called redirect, to the state, and use this to render a Redirect Component to="/topic", I redirect after posting some data to the api.

In topicList when it reloads via Redirect, componentDidMount() is not running so the api call to fetch the newly posted data does not occur.

What is the best way to refetch data from an api call, after reloading the same route via Redirect from react-router.

class PostTopic extends Component


state = {
  redirect: false
}

handleSubmit = (e) => {
  e.preventDefault();
  const { body, subject } = this.state;
  api.postTopic(this.props.store.token,subject,body)
  .then( response => {
     this.setState({redirect:true})
   })
   .catch( error => {
      this.setState({error});
   });
}

renderRedirect = () => {
  if(this.state.redirect){
    return <Redirect to={this.props.currentPath}/>
  }
}

render(){
  return(
     ...
     ...
     ...
     {this.renderRedirect()}                
  }
}

解决方案

componentDidMount will only be run when the component is initially mounted in the DOM, and when a URL parameter changes a new component is not mounted.

You need to use componentDidUpdate and check if the URL parameter has changed and fetch your data again if that is the case.

Example

function getData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Array.from({ length: 3 }, () => Math.random()));
    }, 1000);
  });
}

class Page extends React.Component {
  state = { data: [] };

  componentDidMount() {
    getData().then(data => {
      this.setState({ data });
    });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.match.params.pathParam !== this.props.match.params.pathParam) {
      getData().then(data => {
        this.setState({ data });
      });
    }
  }

  render() {
    return (
      <div>
        {this.state.data.map(element => <div key={element}>{element}</div>)}
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Link to="foo"> Foo </Link>
          <Link to="bar"> Bar </Link>
          <Switch>
            <Route path="/:pathParam" component={Page} />
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}

这篇关于通过反应路由器重新加载相同路由后的 API 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆