【问题标题】:How to use query parameters from a URL in MapStateToProps如何在 MapStateToProps 中使用来自 URL 的查询参数
【发布时间】:2021-06-27 18:14:33
【问题描述】:

我在使用 mapStateToProps(state, ownProps) 将查询参数从我的 URL 插入到我的组件的 props 时遇到问题。

我正在尝试将我的网址用作searchState,正如 Dan Abramov 在此问题中的回答所建议的那样:How to sync Redux state and url query params

问题是,我无法从ownProps 访问查询参数。

我的 URL 是,例如:http://localhost:3000/courses?language=en&page=3,我想访问页码作为道具。

我认为ownProps 不适用于查询参数(即[...]?language=en&page=3)。我试过这种东西,但它似乎不起作用:

[...]
console.log(props.pageNumber)
[...]
const mapStateToProps = (state, ownProps) => {
  return {
    pageNumber: ownProps.match.params.page
  }
}

您知道如何将我的页码作为来自我的 URL 的 ownProp 访问吗?

提前致谢。

【问题讨论】:

    标签: reactjs redux react-redux react-router


    【解决方案1】:

    我建议使用this.props.location.search 访问componentDidMount 内的查询参数或在安装任何组件时运行的任何方法,而不是访问mapStateToProps

    【讨论】:

      【解决方案2】:

      查询参数不属于match.params 中的params。您必须自己从location 访问它们,并使用浏览器的URLSearchParamsqs 之类的助手来解析它们。有一个demo in the docs 可能会有所帮助。

      这是那个演示的钩子:

      // A custom hook that builds on useLocation to parse
      // the query string for you.
      function useQuery() {
        return new URLSearchParams(useLocation().search);
      }
      

      在您的组件中,您可以使用此钩子访问查询参数并将它们用作选择器函数的参数。

      const query = useQuery();
      
      // query parameters might be `null`
      const language = query.get("language") ?? "en";
      
      // they are always `string` instead of `number`
      const page = parseInt(query.get("page") ?? "1");
      
      // can use these values to select from the store
      const courses = useSelector(selectCourses(language, page))
      

      如果你愿意,你可以解析mapStateToProps 中的location。但 Dan 的回答来自 2016 年,现在 React 钩子更有意义,至少在我看来。

      【讨论】:

        猜你喜欢
        • 2021-08-09
        • 1970-01-01
        • 2017-12-02
        • 2020-09-19
        • 2017-12-19
        • 1970-01-01
        • 2018-08-23
        • 2017-04-05
        • 1970-01-01
        相关资源
        最近更新 更多