【问题标题】:Update URL with value from input on click with React使用 React 单击时使用输入值更新 URL
【发布时间】:2017-08-07 07:58:31
【问题描述】:

我正在尝试获取要捕获的输入值,然后使用该值更新部分 URL,所有这些都通过使用 React、ES6 等进行简单的点击来完成。基本上是一个简单的搜索功能

所以我的组件看起来像这样:

class SearchInput extends Component {
  constructor() {
    super()

    this.state = {
      query: ''
    }
  }

  componentDidMount = () => {
    const handleSearchURL = window.location('/search/'+this.state.query+'/some-action')
    this.setState({
      handleSearch: handleSearchURL
    })
  }

  queryChange = (evt) => {
    this.setState({query: evt.target.value})
  }

  render() {
    const { handleSearch, placeholder } = this.props
    return (
      <form>
        <input id="site-search" type="search" placeholder={placeholder} value={this.state.query} />
        <input type="submit" value="Search" onClick={this.handleSearch} />
      </form>
    )
  }
}

但这只会给我很多错误,而且它似乎不喜欢 window.location。实现这一目标的最佳方法是什么?我正在使用 react-router,所以如果有更好的方法,我也很高兴

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-router


    【解决方案1】:

    这对我有用 react-hooks 和 react-router v5

    import { useHistory } from 'react-router-dom';
    
     const history = useHistory();
    
    const handleSubmit = (e) => {
        e.preventDefault();
        history.push(`/search/${input}`);
      };
    

    https://reactrouter.com/web/api/Hooks

    【讨论】:

      【解决方案2】:

      函数 updateQueryStringParam(key, value, location) { 常量 urlQueryString = location.search; 常量 newParam = ${key}=${value}; 让参数 = ?${newParam};

      // 如果“搜索”字符串存在,则从它构建参数 如果(urlQueryString){ const updateRegex = new RegExp(([?&amp;])${key}[^&amp;]*); const removeRegex = new RegExp(([?&amp;])${key}=[^&amp;;]+[&amp;;]?);

      if (typeof value === 'undefined' || value == null || value === '') {
        // Remove param if value is empty
        params = urlQueryString.replace(removeRegex, '$1');
        params = params.replace(/[&;]$/, '');
      } else if (urlQueryString.match(updateRegex) !== null) {
        // If param exists already, update it
        params = urlQueryString.replace(updateRegex, `$1${newParam}`);
      } else {
        // Otherwise, add it to end of query string
        params = `${urlQueryString}&${newParam}`;
      }
      

      }

      // 没有设置参数所以我们不需要问号 返回(参数=参数==='?'?'':参数); }

      const url = updateQueryStringParam('filter', inputValue, this.props.location);

      this.props.history.push(url);

      【讨论】:

        【解决方案3】:

        您可以使用'react-router' 中的"browserHistory",然后将新网址推送到此处,如下所示:

        browserHistory.push('/search/{this.state.query}/some-action')
        

        【讨论】:

        【解决方案4】:

        您可以使用browserHistory.pushthis.context.router.push。 componentDidMount 也是一个生命周期函数,不需要绑定,只执行一次。您还需要一个 handleSearch 函数和一个 onChange 输入查询更改事件

        class SearchInput extends Component {
          constructor() {
            super()
        
            this.state = {
              query: ''
            }
          }
          static contextTypes = {
               router: React.PropTypes.object
           }
          
          handleSearch = () => {
                 this.context.router.push(`'/search/${this.state.query}/some-action'`);
          }
          queryChange = (evt) => {
            this.setState({query: evt.target.value})
          }
        
          render() {
            const { handleSearch, placeholder } = this.props
            return (
              <form>
                <input id="site-search" type="search" placeholder={placeholder} value={this.state.query} onChange={this.queryChange} />
                <input type="submit" value="Search" onClick={this.handleSearch} />
              </form>
            )
          }
        }

        【讨论】:

        • Doesnt' 似乎工作,我在提交时在控制台中收到“无法读取未定义的属性推送”
        • static contextTypes = { router: React.PropTypes.object } 更新了答案检查
        猜你喜欢
        • 1970-01-01
        • 2020-09-03
        • 2018-01-02
        • 2023-04-03
        • 2019-05-03
        • 1970-01-01
        • 2015-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多