React/クエリストリングを処理する
キーワード
- React
- react-router
- Query string
- URLSearchParams
したいこと
- クエリストリングを受け取って状態を初期化する
- ボタンクリックなどで状態を変更してURL(クエリストリング)も変更する
どうやって
最終的には次のような形にできる。
class Hoge extends React.Component {
// this.update()で状態を初期化する
componentDidMount() {
this.update(this.props)
}
// ボタンクリックなどで
// 新しいクエリストリングを作成してURLを変更する
// ここでは状態を変更しない
refresh() {
const { location, history } = this.props
const { search } = location
const reconstructedSearch = ※ 新しいクエリストリング(search)を作成する
history.push({
search: reconstructedSearch
})
}
// 新しいpropsを受け取ったとき
// this.update()で状態を変更する
// ただし、クエリストリングの変更があったときだけ
componentWillReceiveProps(nextProps) {
if (nextProps.location.search === this.props.location.search) return
this.update(nextProps)
}
// 状態を初期化(または変更)する
update(props) {
※ props(this.propsかnextProps)を使って状態を初期化・変更する
}
}
ちなみに
searchの分解や再構成はURLSearchParamsを使えば楽にできる。
参考
作成日 2018-01-18
