API call after reloading same route via react router

时光怂恿深爱的人放手 提交于 2020-01-10 03:15:39

问题


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()}                
  }
}

回答1:


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>
    );
  }
}


来源:https://stackoverflow.com/questions/51751075/api-call-after-reloading-same-route-via-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!