【问题标题】:Build dynamic URLs in React based on input根据输入在 React 中构建动态 URL
【发布时间】:2018-01-12 10:17:45
【问题描述】:

我有一个项目列表,我想过滤它们。

为了做到这一点,我有一个如下所示的过滤组件:

[ text input "item name" ] [ dropdown "item category" ] [ date picker ]

我将 React 与 Redux、react-redux 和 react-router 一起使用。我的组件中没有“过滤器”,我希望在我输入时过滤项目。

首先我不确定我应该如何动态创建 URL,例如,如果您在第一个输入中键入“Abc”,我希望当前 URL 为:

http://example.com/currentPage?filter=Abc&category=&dates=

当我键入时,我希望 URL 不断变化,因此 URL 实际上是在我键入/从下拉列表/日期选择器中选择选项时构建的。我如何使用 React Router 实现这一点?

谢谢

【问题讨论】:

    标签: reactjs url filter redux react-router


    【解决方案1】:

    这很简单。只需将 onChange 函数添加到您的输入字段。如下所示。

    import React from 'react';
    
    class Filter extends React.Component {
      constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {
          filter: '',
          category: '',
          dates: '',
        }
      }
    
      handleChange(evt) {
        this.setState({
          filter: evt.target.value,
        }, () => {
          this.props.fetchFilteredItems(`http://example.com/currentPage?filter=${this.state.filter}&category=${this.state.category}&dates=${this.state.dates}`); // I assumed fetchFilteredItems comes from redux as an action.
        });
      }
    
      render() {
        return (
          <div>
            <input onChange={this.handleChange} />
            <YourDropdown />
            <YourDatePicker />
          </div>
        );
      }
    
    }
    

    希望这能解决您的问题。

    【讨论】:

    • 你认为在基于 Redux 的应用程序中使用“setState”是个好主意吗?因为它肯定看起来像是一种反模式。另外,如果有人只是输入 http://example.com/currentPage?filter=Abc&amp;category=&amp;dates= 怎么办 - 没有任何反应,因为输入没有变化。
    • 我刚刚添加它是为了向您展示演示代码。无论如何,你可以在你的 props 中使用 redux 状态。只需使用它来代替setState 函数即可。
    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多