回答:
アプリにメインページコンポーネントを含めると、多くの場合、次の<Route>ようなコンポーネントでラップされます。
<Route path="/movies" component={MoviesIndex} />
これを行うことにより、 MoviesIndexコンポーネントはにアクセスthis.props.historyできるため、でユーザーをリダイレクトできますthis.props.history.push。
一部のコンポーネント(通常はヘッダーコンポーネント)はすべてのページに表示されるため、 <Route>:で。
render() {
return (<Header />);
}
これは、ヘッダーがユーザーをリダイレクトできないことを意味します。
この問題を回避するには、ヘッダーコンポーネントをwithRouter関数にラップします(エクスポートする場合)。
export default withRouter(Header)
これにより、Headerコンポーネントがにアクセスthis.props.historyできるようになります。つまり、ヘッダーでユーザーをリダイレクトできるようになります。
historyか、matchデフォルトでは存在しませんか?つまり、なぜwithRouter明示的に言及する必要があるのですか?
withRouterレンダリングされるたびにmatch、最も近いルートの、current location、およびhistorypropsをラップされたコンポーネントに渡す高次コンポーネントです。コンポーネントをルーターに接続するだけです。
すべてのコンポーネント、特に共有コンポーネントがそのようなルーターの小道具にアクセスできるわけではありません。ラップされたコンポーネント内で、locationprop にアクセスして、などの詳細情報を取得しlocation.pathnameたり、を使用してユーザーを別のURLにリダイレクトしたりできますthis.props.history.push。
以下はgithubページの完全な例です。
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
詳細については、こちらをご覧ください。
withRouter高次コンポーネントを使用すると、historyオブジェクトのプロパティと最も近いプロパティにアクセスできます<Route>の一致に。withRouter更新渡しますmatch、locationと、historyそれがレンダリングするたび包まコンポーネントに小道具。
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
withRouterは、最も近いルートを渡し、場所に関するプロパティへのアクセスを取得し、コンポーネントにあるプロパティをコンポーネントに配置した場合にのみアクセスできる小道具から一致する高次コンポーネントです。
<Route to="/app" component={helo} history ={history} />
場所を変更してthis.props.history.pushを使用できるように、一致と場所の繁栄を同じにする必要があります。コンポーネントのプロパティごとに提供する必要がありますが、WithRouterを使用すると、プロパティ履歴を追加せずに場所にアクセスして一致させることができます。各ルートからプロパティ履歴を追加せずに方向にアクセスできます。
withRouterようにmatch、およびへのアクセスも許可しlocationます。ユーザーのリダイレクトがの唯一の使用例ではないので、受け入れられた回答がそれを述べているとよいでしょうwithRouter。それ以外の場合、これは素晴らしい自己qnaです。