javascript - 通过 React 路由器重新加载相同路由后的 API 调用

标签 javascript reactjs react-router-v4

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

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

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

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

在通过 React-router 的重定向重新加载同一路由后,从 api 调用重新获取数据的最佳方法是什么。

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 只会在组件最初安装在 DOM 中时运行,并且当 URL 参数更改时不会安装新组件。

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

示例

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

关于javascript - 通过 React 路由器重新加载相同路由后的 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751075/

相关文章:

javascript - React-Redux 更改值的状态不会反射(reflect)在更改上

reactjs - react-router 4 中 IndexRoute 的替代方案

javascript - jvectormap 合并两个 map

javascript - D3 : how to select the div from multiple divs with the same class by the inner html in D3?

javascript - 我将如何/在 Node 中使用什么来抓取 <video> src?

javascript - 如何在ReactJS中动态设置元素名称

javascript - 插入 React Link 组件并将其作为 prop 传递

reactjs - 我在 Laravel Mix 中使用 React 路由器刷新浏览器时收到错误 404

javascript - jQuery 函数作为其他 jQuery 函数的参数不起作用

javascript - 意外的 JSON 行为