【问题标题】:How to save bad invalid URLs that were typed in?如何保存输入的无效 URL?
【发布时间】:2019-04-22 19:40:52
【问题描述】:

我在应用内有一个 react-redux 应用和 react-router v4

有没有办法捕获所有输入的无效 URL 并将它们保存到数组中,例如 ['https://mysite.co/progects', 'https://mysite.co/sometypo', 'https://mysite.co/something']

然后我想将该数据发送到服务器以构建一些重定向和一些站点地图

目前我有这个:

 <Switch>
              {/* <Route path='/blog' exact component={Blog} /> */}
              <Route path='/projects/:id' component={ProjectDetails} />
              <Route path='/career/:id' component={CareerDetails} />
              <Route path='/apply-for-job' render={(props) => (
                <ModalWindow
                  {...props}
                  modalHeader='Apply form'>
                  <ApplyForm history={props.history} />
                </ModalWindow>
              )} />
              <Route exact path='/' component={withScrollPreservation(LandingPage)} />
              <Route component={NoMatch} />
              {/* <Route component={withScrollPreservation(LandingPage)} /> */}
            </Switch>

【问题讨论】:

    标签: reactjs redirect react-router sitemap


    【解决方案1】:

    在您的 NoMatch 组件中,您可以拥有更新不匹配/不正确 url 的逻辑

    class NoMatch extends React.Component {
       componentDidMount() {
         const { addNoMatchUrl } = this.props;
         // you might want to handle the duplicate url logic here too in addNoMatchUrl method
         addNoMatchUrl(this.props.location.pathname);
       }
       componentDidUpdate(prevProps) {
          const { location, addNoMatchUrl } = this.props;
          if (location.pathname !== prevProps.location.pathname) {
              addNoMatchUrl(location.pathname);
          }
       }
       render() {
          // render logic
       }
    }
    
    export default connect(null, {addNoMatchUrl});
    

    【讨论】:

      【解决方案2】:

      如果你想将输入'/progects' 的人重定向到'/projects' - 嗯,这是很好的用户体验,但你的Switch 块将被数十个可能的无效网址弄乱。 在我看来,也许您应该在 Switch 的底部添加 &lt;Redirect to='/main' /&gt;,以便将任何无效的 url 重定向到 Main 组件(或任何您拥有的组件)或 404-Component。

      如果您仍想收集它们,那么不要重定向到 Main 或 404 组件,而是将它们发送到特定的 Error 组件,在那里您可以通过 this.props.history.location 获取链接并在组件中进一步处理该链接:发送到服务器,在本地/会话存储中设置该 url,等等。

      请注意,您需要一种将数据存储在卸载时不会被清除的地方的方法。

      为了将用户发送到该路线,您需要将其放在 Switch 的底部。

      <Switch>
          ...{your routes}
          <Route component={Error} />
      </Switch>
      

      所以实际上你需要做的就是在你的 NoMatch 组件中处理这些 url,就像这样

      const path = this.props.history.location;
      axios.post('your api', path);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多