反应路由器传递 variable/state 到新路线?
react router passing variable/state to new route?
我有一个在一个组件中创建的动态变量,然后该组件路由到另一个组件。我如何传递变量?
组件 A
import React, { Component } from 'react';
class Event extends React.Component {
makeVariable(event)
{ myVariable = '123abc' }
{window.location.replace("/B")}
render () { return (html for page A)
}
export default A;
组件 B
import React, { Component } from 'react';
class B extends Component {
render(){ console.log(myVariable)}
}
export default B;
路线文件
export const makeMainRoutes = () => {
return (
<Router history={history}>
<div>
<Route path="/A" render={(props) => <App auth={auth} {...props} />} />
<Route path="/B" render={(props) => <Home auth={auth} {...props} />} />
)}
在 React Router 4 中,您应该能够通过 props.location.search
.
访问查询参数
组件 A
window.location.replace(`/B?myVariable=${myVariable}`);
组件 B
import queryString from 'query-string';
render() {
console.log(queryString.parse(this.props.location.search).myVariable));
}
我不太确定这是否是您要问的,但我假设是:)
假设这是您要从组件 A 发送到组件 B 的数据。
const yourData = [{name: 'Tom', age: 28}, {name: 'Sara', age: 25}, {name: 'Rick', age: 34}];
您可以使用 Link
标签将数据从一个组件传递到另一个组件,如下所示:
<Link to={{ pathname: `/component/b`, state: { yourData } }}></Link>
[也许添加一个按钮标签,这样用户可以点击它,转到下一条路线,必要的数据将被传递] ...然后,在组件 B 中,您可以访问您的数据,例如这个:
const passedData= this.props.history.location.state.yourData;
我有一个在一个组件中创建的动态变量,然后该组件路由到另一个组件。我如何传递变量?
组件 A
import React, { Component } from 'react';
class Event extends React.Component {
makeVariable(event)
{ myVariable = '123abc' }
{window.location.replace("/B")}
render () { return (html for page A)
}
export default A;
组件 B
import React, { Component } from 'react';
class B extends Component {
render(){ console.log(myVariable)}
}
export default B;
路线文件
export const makeMainRoutes = () => {
return (
<Router history={history}>
<div>
<Route path="/A" render={(props) => <App auth={auth} {...props} />} />
<Route path="/B" render={(props) => <Home auth={auth} {...props} />} />
)}
在 React Router 4 中,您应该能够通过 props.location.search
.
组件 A
window.location.replace(`/B?myVariable=${myVariable}`);
组件 B
import queryString from 'query-string';
render() {
console.log(queryString.parse(this.props.location.search).myVariable));
}
我不太确定这是否是您要问的,但我假设是:)
假设这是您要从组件 A 发送到组件 B 的数据。
const yourData = [{name: 'Tom', age: 28}, {name: 'Sara', age: 25}, {name: 'Rick', age: 34}];
您可以使用 Link
标签将数据从一个组件传递到另一个组件,如下所示:
<Link to={{ pathname: `/component/b`, state: { yourData } }}></Link>
[也许添加一个按钮标签,这样用户可以点击它,转到下一条路线,必要的数据将被传递] ...然后,在组件 B 中,您可以访问您的数据,例如这个:
const passedData= this.props.history.location.state.yourData;