리액션 라우터의 쿼리 매개 변수를 프로그래밍 방식으로 업데이트하는 방법은?
사용하지 않고 react-router로 쿼리 매개 변수를 업데이트하는 방법을 찾을 수 없는 경우<Link/>
.hashHistory.push(url)
쿼리 매개 변수를 등록하지 않는 것 같고, 쿼리 개체나 어떤 것도 두 번째 인수로 전달할 수 없는 것 같다.
URL을 변경하는 방법/shop/Clothes/dresses
로/shop/Clothes/dresses?color=blue
사용하지 않고 반응하여<Link>
?
그리고 이다onChange
기능 정말로 쿼리 변경을 청취할 수 있는 유일한 방법인가?쿼리 변경 내용이 매개 변수 변경과 같은 방식으로 자동으로 탐지 및 대응되지 않는 이유는?
내push
의 방법.hashHistory
, 쿼리 매개 변수를 지정할 수 있다.예를 들어.
history.push({
pathname: '/dresses',
search: '?color=blue'
})
또는
history.push('/dresses?color=blue')
이 리포지토리에서 사용 방법에 대한 추가 예제를 확인하십시오.history
react-router v4, reducedx-thunk 및 react-router-redex(5.0.0-alpha.6) 패키지 사용 예.
사용자가 검색 기능을 사용할 때, 나는 그가 동료에게 동일한 질의에 대한 URL 링크를 보낼 수 있기를 바란다.
import { push } from 'react-router-redux';
import qs from 'query-string';
export const search = () => (dispatch) => {
const query = { firstName: 'John', lastName: 'Doe' };
//API call to retrieve records
//...
const searchString = qs.stringify(query);
dispatch(push({
search: searchString
}))
}
존의 대답은 정확하다.내가 파람을 다룰 때 나는 또한 필요하다.URLSearchParams
인터페이스:
this.props.history.push({
pathname: '/client',
search: "?" + new URLSearchParams({clientId: clientId}).toString()
})
또한 구성 요소를 다음과 같이 포장해야 할 수 있다.withRouter
HORK 예.export default withRouter(YourComponent);
.
변경 시마다 새 경로를 푸시하는 대신 교체 기능을 사용할 수 있음
import React from 'react';
import { useHistory, useLocation } from 'react-router';
const MyComponent = ()=>{
const history = useHistory();
const location = useLocation();
const onChange=(event)=>{
const {name, value} = event?.target;
const params = new URLSearchParams({[name]: value });
history.replace({ pathname: location.pathname, search: params.toString() });
}
return <input name="search" onChange={onChange} />
}
이렇게 하면 모든 변경에 대해 새로운 경로를 적용하는 대신 역사를 보존할 수 있다.
업데이트 - 2022년 2월(V6)
매트릭스에 의해 지적된 대로, 스필트 useHistory는 변화를 만들기 위해 useNavigate로 대체되었다.또한 useSearchParams라는 편리한 방법이 있다. 설명서를 읽기만 하면 되고 실행하지 않아도 된다. 그러나 이 방법은 효과가 있을 것이다.
import React from 'react';
import { useSearchParams } from 'react-router-dom';
// import from react-router should also work but following docs
// import { useSearchParams } from 'react-router';
const MyComponent = ()=>{
const [searchParams, setSearchParams] = useSearchParams();
const onChange=(event)=>{
const {name, value} = event?.target;
setSearchParams({[name]: value})
}
return <input name="search" onChange={onChange} />
}
for react-router v4.3,
const addQuery = (key, value) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.set(key, value);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
const removeQuery = (key) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.delete(key);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
```
```
function SomeComponent({ location }) {
return <div>
<button onClick={ () => addQuery('book', 'react')}>search react books</button>
<button onClick={ () => removeQuery('book')}>remove search</button>
</div>;
}
```
// To know more on URLSearchParams from
[Mozilla:][1]
var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
[1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
당신은 훅을 사용할 수 있다.useHistory
사용 중인지 확인하십시오.function
based 구성 요소 맨 위에 있는 항목
import {useHistory} from "react-router-dom"
당신의 구성 요소에서,
const history = useHistory()
history.push({
pathname: window.location.pathname,
search: '?color=blue'
})
import { browserHistory } from 'react-router';
/**
* @param {Object} query
*/
export const addQuery = (query) => {
const location = Object.assign({}, browserHistory.getCurrentLocation());
Object.assign(location.query, query);
// or simple replace location.query if you want to completely change params
browserHistory.push(location);
};
/**
* @param {...String} queryNames
*/
export const removeQuery = (...queryNames) => {
const location = Object.assign({}, browserHistory.getCurrentLocation());
queryNames.forEach(q => delete location.query[q]);
browserHistory.push(location);
};
또는
import { withRouter } from 'react-router';
import { addQuery, removeQuery } from '../../utils/utils-router';
function SomeComponent({ location }) {
return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
<button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
<button onClick={ () => removeQuery('paintRed')}>Paint white</button>
</div>;
}
export default withRouter(SomeComponent);
쿼리 문자열을 쉽게 구문 분석할 수 있는 모듈이 필요한 경우 쿼리 문자열 모듈을 사용하는 것이 권장된다.
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
store.dispatch(push("/"));
}
}
여기서, 쿼리 매개 변수로 토큰을 다시 리디렉션하는 Google-Passport 인증확인에 성공한 후 Node.js 서버에서 내 클라이언트로 리디렉션하고 있다.
나는 그것을 쿼리 문자열 모듈로 파싱하고 저장하며 react-router-remensx의 푸시로 URL의 쿼리 매개 변수를 업데이트하고 있다.
이런 식으로도 쓸 수 있다.
this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)
나는 네가 아래 기능을 사용하는 것을 선호한다.ES6
스타일:
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
입력 필드에 입력하는 경우 아래 그림과 같이 React JS function component를 사용하여 브라우저 URL로 쿼리 문자열로 출력
import React, { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'
const Search = () => {
const [query, setQuery] = useState('')
const history = useHistory()
const onChange = (e) => {
setQuery(e.target.value)
}
useEffect(() => {
const params = new URLSearchParams()
if (query) {
params.append('name', query)
} else {
params.delete('name')
}
history.push({ search: params.toString() })
}, [query, history])
return <input type="text" value={query} onChange={onChange} />
}
export default Search
브라우저의 URL 쿼리
/search?name=query_here
@Craque가 설명한 것처럼 우리는 모든 변경에 대해 새로운 경로를 추진하는 대신 교체 기능을 사용할 수 있다.그러나 react-Router 버전 6에서 useHistory()는 함수만 반환하는 useNavigate()로 대체되었다.옵션을 함수에 전달하여 이전 location.replace()와 동일한 효과를 얻을 수 있다.
import { useLocation, useNavigate } from 'react-router-dom';
const to = { pathname: location.pathname, search: newParams.toString() };
navigate(to, { replace: true });
'IT이야기' 카테고리의 다른 글
Rx 사용법.관측 가능.프로토타입.교환원으로 보내시겠습니까? (0) | 2022.03.22 |
---|---|
한 개 또는 여러 개의 인스턴스를 지정하시겠습니까? (0) | 2022.03.22 |
v-data-table 끌어서 놓기 설정 (0) | 2022.03.22 |
페이지 새로 고침 시 Vuex 상태 (0) | 2022.03.22 |
텐서플로우가 python shell 안쪽에서 gpu 가속을 사용하는지 확인하는 방법 (0) | 2022.03.22 |