React Router 6.3.0
Is there a way to be able to pass state and query params in same navigate call, and have both applied?
Steps to Reproduce
Try
navigate( { pathname: "/search", search: `?${createSearchParams({ query: someQuery })}`, state: { someAttributeName: someAttributeValue } } );
Note that the query params are passed in the URL but state will be null.
Try
navigate( "/search", { search: `?${createSearchParams({query: someQuery})}`, state: { someAttributeName: someAttributeValue } } );
Note that the state is passed but the query params are not applied.
React Router 6.3.0
Is there a way to be able to pass state and query params in same navigate call, and have both applied?
Steps to Reproduce
Try
navigate( { pathname: "/search", search: `?${createSearchParams({ query: someQuery })}`, state: { someAttributeName: someAttributeValue } } );
Note that the query params are passed in the URL but state will be null.
Try
navigate( "/search", { search: `?${createSearchParams({query: someQuery})}`, state: { someAttributeName: someAttributeValue } } );
Note that the state is passed but the query params are not applied.
Share Improve this question edited Sep 17, 2022 at 16:30 Drew Reese 204k18 gold badges245 silver badges273 bronze badges asked Sep 17, 2022 at 9:26 Matthew FoyleMatthew Foyle 631 silver badge6 bronze badges2 Answers
Reset to default 3You don't need to append ?
.
navigate(
{
pathname: "/search",
search: createSearchParams({ query: "someQuery" }).toString(),
},
{ state: { someAttributeName: "someAttributeValue" } },
);
The search value can be sent in the To
object in the first argument, and the state as a property in the options
object in the second argument.
useNavigate
declare function useNavigate(): NavigateFunction; interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: any; relative?: RelativeRoutingType; } ): void; (delta: number): void; }
To
type
export type To = string | Partial<Path>;
Partial<Path>
type
/** * The pathname, search, and hash values of a URL. */ export interface Path { /** * A URL pathname, beginning with a /. * * @see https://github./remix-run/history/tree/main/docs/api-reference.md#location.pathname */ pathname: Pathname; /** * A URL search string, beginning with a ?. * * @see https://github./remix-run/history/tree/main/docs/api-reference.md#location.search */ search: Search; /** * A URL fragment identifier, beginning with a #. * * @see https://github./remix-run/history/tree/main/docs/api-reference.md#location.hash */ hash: Hash; }
Your code:
navigate(
{
pathname: "/search",
search: `?${createSearchParams({ query: someQuery })}`,
},
{ state: { someAttributeName: someAttributeValue } },
);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745047650a4608193.html
评论列表(0条)