Reactjs 如何基于URL设置React.useState
我正在尝试根据用户使用window.location.path时所在的页面,将以下数字设置为不同的数字Reactjs 如何基于URL设置React.useState,reactjs,react-router,Reactjs,React Router,我正在尝试根据用户使用window.location.path时所在的页面,将以下数字设置为不同的数字 const [value, setValue] = React.useState(1); 我尝试了if语句,但似乎出现了错误,所以我的想法是将参数设置为 然而,虽然我明白,我可以做一些像 <Route exact path="/:id" component={Home} /> const [value, setValue] = React.useState({pageID})
const [value, setValue] = React.useState(1);
我尝试了if语句,但似乎出现了错误,所以我的想法是将参数设置为
然而,虽然我明白,我可以做一些像
<Route exact path="/:id" component={Home} />
const [value, setValue] = React.useState({pageID});
<Route path="/podcast/:id" pageID="4" component={Podcast} />
我在想
<Route exact path="/:id" component={Home} />
const [value, setValue] = React.useState({pageID});
<Route path="/podcast/:id" pageID="4" component={Podcast} />
我怎样才能做到这一点呢?假设您正在组件
新闻中使用此功能
从链路中提取参数的第一步是使用with router
将其导入组件News
文件:Import{withRouter}来自“react router”代码>
我们需要使用路由器将组件包装在HOC中,如下所示:
假设你想这样做:
const[value,setValue]=React.useState({pageID})代码>
在组件装载时,在componentDidMount
内部,我们可以按如下方式提取参数:
const{id}=this.props.match.params//用户导航到的id:/news/:id
然后您可以使用该id来更新您的状态。假设您正在组件新闻中使用该id
从链路中提取参数的第一步是使用with router
将其导入组件News
文件:Import{withRouter}来自“react router”代码>
我们需要使用路由器将组件包装在HOC中,如下所示:
假设你想这样做:
const[value,setValue]=React.useState({pageID})代码>
在组件装载时,在componentDidMount
内部,我们可以按如下方式提取参数:
const{id}=this.props.match.params//用户导航到的id:/news/:id
然后您可以使用该id来更新您的状态。您可以尝试使用render方法将参数传递给组件
<Switch>
<Route exact path="/" render={(props) => <Home pageId=1 {...props} />} />
<Route path="/about/" render={(props) => <About pageId=2 {...props} />} />
</Switch>
} />
} />
您可以尝试使用render方法将参数传递给组件
<Switch>
<Route exact path="/" render={(props) => <Home pageId=1 {...props} />} />
<Route path="/about/" render={(props) => <About pageId=2 {...props} />} />
</Switch>
} />
} />
您可以将多个参数添加到路径中,如下所示:-
path="/podcast/:id/:pageId"
以及取回—
this.props.match.params.pageId
您可以将多个参数添加到路径中,如下所示:-
path="/podcast/:id/:pageId"
以及取回—
this.props.match.params.pageId