【问题标题】:react/jquery: redirecting to another URL with built query stringreact/jquery:使用内置查询字符串重定向到另一个 URL
【发布时间】:2023-03-24 09:05:01
【问题描述】:

我在我的 react 组件的渲染语句中有一个简单的输入框,如下所示:

render()
    return(
<form onSubmit={this.handleSubmit}>
      <input id="searchbox" type="text" />
</form>
);

使用this.handleSubmit 函数,我想将&lt;input&gt; 的内容重定向到我网站上的另一个URL 端点。具体来说,我想以查​​询字符串的形式将其转发给www.mysite.com/confidence,如下所示:

www.mysite.com/SB=?the%query%string

在handleSubmit() 中重定向到的最佳方式是什么?这是我的伪代码:

 handleSubmit(){
    // contents of search box
    var val = $('#searchbox').val();

    //Create querystring
    var queryString = makeQueryString(val)

    //redirect to /confidence endpoint with built querystring
    redirect('/confidence' + queryString)
}

【问题讨论】:

  • 您的makeQueryString 和redirect 函数是否已经存在?
  • @azium 不,我想知道如何正确重定向。我可以处理构建我相信的查询字符串部分。
  • “正确”是什么意思?你试过location.href = '/newurl' 吗?
  • 我尝试在我的handleSubmit() 函数中运行location.href = '/confidence'; 和window.location="/confidence";,但它似乎什么也没做。页面只是刷新,URL 采用“?”最后。我是不是做错了什么?
  • 也可以试试event.preventDefault() .. handleSubmit(event) { event.preventDefault(); location.href = '/url' }

标签: javascript jquery node.js reactjs


【解决方案1】:

重定向:就像调用location.href = newUrlString一样简单

但是,表单提交似乎具有优先权,因此您需要防止默认行为。

handSubmit(event) {
  event.preventDefault()
  location.href = newUrlString
}

从 React 中的表单获取值:

这里不需要使用 jQuery 来获取 React 组件中的表单值。如果我们需要它,那为什么还要使用 React?页面加载后使用ref回调函数存储节点,并将值传递给您的提交处理程序。

<form onSubmit={event => this.handleSubmit(event, this.inputNode.value)}>
  <input ref={node => this.inputNode = node} type="text" />
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 2014-12-03
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2022-03-24
    相关资源
    最近更新 更多