我的应用程序的根是App。我的App组件使用react-router路由到不同的页面。现在,我只有一个,但还会有更多。每个页面将呈现父组件,其中包含2个子组件。对于每个父组件,一个子组件(让我们称它为Child1)是一个接受一些输入并进行和API调用的表单。另一个组件(让我们称它为Child2)将以表格形式呈现此数据。
我的目标:不同的父母将在不同的路线上呈现:/parent1,/parent2等。我希望Child1在/parent1上呈现,Child2在/parent1?name=something上呈现。查询参数需要保存用户提供的表单输入的值,这样我就可以使它成为一个可共享的URL。任何拥有这些参数的人都应该能够直接看到表格的结果。我该怎么做?
下面是我的一些简化代码:App.js
const App = () => {
return(
<BrowserRouter>
<div>
<ul>
<li>
<Link to="/parent1">Parent-1</Link>
</li>
</ul>
</div>
<hr/>
<Switch>
<Route path="/parent1">
<Parent1 />
</Route>
</Switch>
</BrowserRouter>
);
};Parent1.js
class Parent1 extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [],
isSearched: false
};
};
onFiltersSelected = (products) => {
this.setState({
products: products,
isSearched: true
});
};
render() {
return (
<div>
<Header />
{!this.state.isSearched ?
<Child1 onFiltersSelected={this.onFiltersSelected} /> :
<Child2 products={this.state.products} />}
</div>
);
};
};Child1.js
onFormSubmit = (e) => {
// make API call and call onFiltersSelected from Parent1
};
.......
render() {
return (
<div className="container container-fluid">
.........
.........
<div className="row">
<button type="submit" className="btn btn-primary">Search Instances</button>
</div>
</form>
</div>
);
};Child2.js
class Child2 extends React.Component {
render() {
return (
<div className="container">
....
</div>
);
};
};发布于 2020-06-24 18:35:26
如果您将Parent1的Route定义为<Route path="/parent1" component={Parent1}/>,React将传递一些道具,比如location。您只需执行props.location.name并测试它。如果为null,则呈现Child1,如果不是,则呈现Child2。
来源:https://learnwithparam.com/blog/how-to-handle-query-params-in-react-router/
发布于 2020-06-24 19:18:05
可以从npm 链接在这里安装查询字符串包,以接收使用解析方法的查询字符串。
import QueryString from 'query-string'
const qr = queryString.parse(props.location.search)解析方法接收location.search对象,该对象来自props,包含通过查询字符串传递的键和值。
然后,您可以根据接收到的值创建呈现组件的条件。
https://stackoverflow.com/questions/62561781
复制相似问题