reactjs - 如何将 React Router 参数与状态同步

标签 reactjs react-hooks react-router-dom

使用 React Router Web。

假设我们有一条路线:/:user?showDetails=true。我们知道如何从带有 useParams 的 URL 中获取数据钩子(Hook)和类似 useQuery 的东西自定义 Hook 。

此外,我们知道如何使用 history.push(/baruchiro?showDetails=false)设置此数据。 .

但是如果我们获取并设置这个数据,并且如果我们不使用它来将用户从一个页面重定向到另一个页面,而是更改当前组件(让用户保存其当前页面 View ),它是表示路线

如何使用路由作为状态而不用大量 history.pushuseParams 弄脏组件?

最佳答案

更新

我将此自定义 Hook 发布为 npm 包:use-route-as-state


如果你想使用route作为state,你需要一种方法来获取路由参数,并且更新他们。

您无法避免使用 history.push,因为这是您更改“状态”、路线 的方式。但是您可以隐藏此命令以获得更清晰的代码。

这是一个示例,说明如何在自定义 Hook 中隐藏 getupdate,使它们看起来像常规的 useState钩子(Hook):

使用查询参数作为状态:

import { useHistory, useLocation} from 'react-router-dom'

const useQueryAsState = () => {
    const { pathname, search } = useLocation()
    const history = useHistory()

    // helper method to create an object from URLSearchParams
    const params = getQueryParamsAsObject(search)

    const updateQuery = (updatedParams) => {
        Object.assign(params, updatedParams)
        // helper method to convert {key1:value,k:v} to '?key1=value&k=v'
        history.replace(pathname + objectToQueryParams(params))
    }

    return [params, updateQuery]
}

使用路由参数作为状态:

import { generatePath, useHistory, useRouteMatch } from 'react-router-dom'

const useParamsAsState = () => {
    const { path, params } = useRouteMatch()
    const history = useHistory()

    const updateParams = (updatedParams) => {
        Object.assign(params, updatedParams)
        history.push(generatePath(path, params))
    }
    return [params, updateParams]
}

Note to the history.replace in the Query Params code and to the history.push in the Route Params code.

用法:(不是我代码中的真实组件,如果存在编译问题,请见谅)

const ExampleComponent = () => {
    const [{ user }, updateParams] = useParamsAsState()
    const [{ showDetails }, updateQuery] = useQueryAsState()

    return <div>
        {user}<br/ >{showDetails === 'true' && 'Some details'}
        <DropDown ... onSelect={(selected) => updateParams({ user: selected }) />
        <Checkbox ... onChange={(isChecked) => updateQuery({ showDetails: isChecked} })} />
    </div>
}

关于reactjs - 如何将 React Router 参数与状态同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63685178/

相关文章:

javascript - 在自定义 Hook 和组件中使用 useEffect 有什么区别

javascript - useCallback 并传入参数

reactjs - 如何在驻留在使用从 React Router 构建的嵌套 URL 的子目录上的 SPA React 应用程序上正确配置 Apache?

javascript - React 项目中正确路由的问题

attributes - 如何从引用选择器操作属性

javascript - 在 React Native 日历中突出显示按下(选定)的日期

javascript - 使用内部表填充动态表 - JavaScript

reactjs - React JSX错误: Unclosed regular expression

reactjs - enzyme 和 react 路由器: How to shallow render a component with useHistory

reactjs - 与 Gatsby react 路由器