在本文中,您将会了解到关于使用ReactRouterV4以编程方式导航的新资讯,同时我们还将为您解释reactrouter教程的相关在本文中,我们将带你探索使用ReactRouterV4以编程方式导航
在本文中,您将会了解到关于使用React Router V4以编程方式导航的新资讯,同时我们还将为您解释react router教程的相关在本文中,我们将带你探索使用React Router V4以编程方式导航的奥秘,分析react router教程的特点,并给出一些关于javascript – 如何以编程方式从React Router 4.0中的事件处理程序导航到路由?、react-router – 使用React-Semantic-UI CardGroups配置React Router SubRoutes、react-router-v4 – 如何创建react-router v4 breadcrumbs?、reactjs – React Native(使用Redux)动画切换以编程方式的实用技巧。
本文目录一览:- 使用React Router V4以编程方式导航(react router教程)
- javascript – 如何以编程方式从React Router 4.0中的事件处理程序导航到路由?
- react-router – 使用React-Semantic-UI CardGroups配置React Router SubRoutes
- react-router-v4 – 如何创建react-router v4 breadcrumbs?
- reactjs – React Native(使用Redux)动画切换以编程方式
使用React Router V4以编程方式导航(react router教程)
我刚刚react-router
从v3 替换为v4。
但是我不确定如何以编程方式在的成员函数中进行导航Component
。即在handleClick()
功能上我想导航到/path/some/where
处理一些数据后。我曾经通过以下方式做到这一点:
import { browserHistory } from ''react-router''browserHistory.push(''/path/some/where'')
但是我在v4中找不到这样的接口。
如何使用v4导航?
答案1
小编典典如果您定位到浏览器环境,则需要使用react-router-dom
package而不是react-router
。他们按照相同的方法作出反应那样,以核心分开,( react
)和特定于平台的代码,( react-dom
,react-native
用细微的差别,你并不需要安装两个独立的包),这样的环境包包含一切你需要。您可以通过以下方式将其添加到项目中:
yarn add react-router-dom
要么
npm i react-router-dom
您需要做的第一件事是<BrowserRouter>
在应用程序中提供一个作为最顶层的父组件。<BrowserRouter>
使用HTML5history
API并为您管理它,因此您不必担心自己实例化并将其<BrowserRouter>
作为道具传递给组件(就像在以前的版本中一样)。
在V4中,要以编程方式进行导航,您需要访问history
对象(可通过React 进行访问)context
,只要您将<BrowserRouter>
提供程序
组件作为应用程序中最顶层的父对象即可。该库通过上下文公开router
本身包含history
为属性的对象。该history
接口提供多种导航方法,比如push
,replace
和goBack
,等等。您可以在此处检查属性和方法的完整列表。
给Redux / Mobx用户的重要说明
如果您将redux或mobx用作应用程序中的状态管理库,则可能遇到了组件问题,这些组件应该是位置感知的,但在触发URL更新后不会重新呈现
这是因为使用上下文模型react-router
传递location
给组件。
connect和observer都创建了组件,这些组件的shouldComponentUpdate方法对当前道具和下一个道具进行了浅层比较。只有更改了至少一个道具后,这些组件才会重新渲染。这意味着,为了确保它们在位置更改时更新,需要为它们提供一个在位置更改时更改的道具。
解决此问题的2种方法是:
- 将 连接的 组件包裹在无路可走的地方
<Route />
。当前location
对象是a<Route>
传递给它渲染的组件的道具之一 - 将 连接的 组件与
withRouter
高阶组件包装 在一起 ,实际上其效果和注入location
与道具相同
抛开这些,有四种编程方式进行导航,并按建议进行排序:
1.-使用<Route>
组件
它提倡一种声明式风格。在v4之前,<Route />
组件被放置在组件层次结构的顶部,必须事先考虑您的路由结构。但是,现在您可以在树中的 任何位置*
拥有<Route>
组件,从而使您可以更好地控制根据URL进行有条件的呈现。向组件注入,并作为道具。导航方法(如,,…)都可以作为属性对象。
*Route``match``location``history``push``replace``goBack``history
有3种方法可以Route
通过使用component
,render
或children
道具来用a渲染某些事物,但在同一内不要使用多个Route
。选择取决于用例,但是基本上前两个选项仅在path
匹配url位置时才呈现组件,而children
无论路径是否匹配位置,都将呈现组件(可用于基于URL调整UI匹配)。
如果要自定义组件渲染输出
,则需要将组件包装在函数中并使用render
选项,以便将所需的其他道具match
(location
和除外)传递给组件history
。一个例子来说明:
import { BrowserRouter as Router } from ''react-router-dom''const ButtonToNavigate = ({ title, history }) => ( <button type="button" onClick={() => history.push(''/my-new-location'')} > {title} </button>);const SomeComponent = () => ( <Route path="/" render={(props) => <ButtonToNavigate {...props} title="Navigate elsewhere" />} />)const App = () => ( <Router> <SomeComponent /> // Notice how in v4 we can have any other component interleaved <AnotherComponent /> </Router>);
2.-使用withRouter
HoC
这个更高阶的成分将注入与相同的道具Route
。但是,它带有一个限制,即每个文件只能有1个HoC。
import { withRouter } from ''react-router-dom''const ButtonToNavigate = ({ history }) => ( <button type="button" onClick={() => history.push(''/my-new-location'')} > Navigate </button>);ButtonToNavigate.propTypes = { history: React.PropTypes.shape({ push: React.PropTypes.func.isRequired, }),};export default withRouter(ButtonToNavigate);
3.-使用Redirect
组件
渲染<Redirect>
会导航到新位置。但是请记住, 默认情况下 ,当前位置会被新位置替换,例如服务器端重定向(HTTP
3xx)。新位置由to
prop 提供,可以是字符串(重定向到的URL)或location
对象。如果您想 将新条目推送到历史记录中
,则还传递一个push
道具并将其设置为true
<Redirect to="/your-new-location" push />
4.- router
通过上下文手动访问
有点气is,因为上下文仍然是一个实验性的API,它可能会在React的未来版本中中断/更改
const ButtonToNavigate = (props, context) => ( <button type="button" onClick={() => context.router.history.push(''/my-new-location'')} > Navigate to a new location </button>);ButtonToNavigate.contextTypes = { router: React.PropTypes.shape({ history: React.PropTypes.object.isRequired, }),};
不用说,还有一些其他路由器组件将用于非浏览器生态系统,例如 在内存<NativeRouter>
中复制导航堆栈并定位到React
Native平台(可通过软件包获得)。 __react-router-native
有关更多参考,请随时查看官方文档。该库的一位合著者还制作了一个视频,其中对React-
router v4进行了非常酷的介绍,重点介绍了一些主要更改。
javascript – 如何以编程方式从React Router 4.0中的事件处理程序导航到路由?
自从以前的版本以来,这似乎已经改变了
以前我们会这样做:
import { browserHistory } from 'react-router'; ... handleClick(){ doSomething(); browserHistory.push('/some/path'); }
解决方法
我们有3个组成部分:
> App.js – 包含组件1和组件2
> Component1.js – 没有包裹在路线中并且将始终被渲染,但是这将没有“路径道具”的引用 – (历史,位置,匹配……)
> Component2.js – 仅在路线位置匹配时呈现.需要注意的是,此组件将使用“路径道具”进行渲染
要以编程方式导航,可以使用react-router history对象.
this.props.history.push( ‘路径’);
对于通过Route呈现的组件,这将立即起作用,因为这些组件已经可以访问路径道具(历史).在我们的示例中,这是Component2.但是,对于未通过Route(例如Component1)呈现的组件,您需要将其包装在withRouter中,以便您访问历史对象.
App.js
import React,{ Component } from 'react'; import { browserRouter,Route } from 'react-router-dom'; import Component1 from './Component1'; import Component2 from './Component2'; class App extends Component { render() { return ( <browserRouter> <div> <Component1 /> <Route path="/render1" render={() => <div>Rendered from Component1</div>} /> <Route path="/" component={Component2} /> <Route path="/render2" render={() => <div>Rendered from Component2</div>} /> </div> </browserRouter> ) } } export default App;
Component1.js
import React from 'react'; import { withRouter } from 'react-router'; class Component1 extends React.Component { handleButtonClick() { this.props.history.push('/render1'); } render() { return ( <div> <h1>Component 1</h1> <button onClick={this.handleButtonClick.bind(this)}>Component 1 Button</button> </div> ); } } const Component1WithRouter = withRouter(Component1); export default Component1WithRouter;
对于Component1,我们将它包装在withRouter中,然后导出返回的包装对象.有些人注意到,在App.js中,我们仍然将其引用为Component1而不是Component1WithRouter
Component2.js
import React from 'react'; class Component2 extends React.Component { handleButtonClick() { this.props.history.push('/render2'); } render() { return ( <div> <h1>Component 2</h1> <button onClick={this.handleButtonClick.bind(this)}>Component 2 Button</button> </div> ); } } export default Component2;
对于Component2,历史对象已经可以从this.props获得.你只需要调用push函数.
react-router – 使用React-Semantic-UI CardGroups配置React Router SubRoutes
This issue on github带我到了semantic-ui-react documentation on Augmentation,
以及setting up route config with sub-routes上的react-router文档.
我的路由配置似乎有效,但目前还不清楚具体实现组件扩充的位置.
我试过< Card.Group items = {items} as = {Link} to = {items.map((item,i)=>(item.href))} /> ;,以及试图把道具本身中的as = {Link},并且遇到了一堆错误,最终递归失败导致可怕的最大调用堆栈大小超出!
现在,我只是使用react-router对组件的路径进行硬编码.功能性方法会更优雅,反应更灵敏,这就是我所追求的!
因此,子组件API的正确用法是:
<Card.Group> <Card as={Link} to='/foo' /> <Card as={Link} to='/bar' /> </Card.Group>
正确使用速记API的方法是:
const items = [ { as: Link,content: 'Foo',to: '/foo' },{ as: Link,content: 'Bar',to: '/bar' },] <Card.Group items={items} />
react-router-v4 – 如何创建react-router v4 breadcrumbs?
这对我有用:
const Breadcrumbs = (props) => ( <div className="breadcrumbs"> <ul className='container'> <Route path='/:path' component={BreadcrumbsItem} /> </ul> </div> ) const BreadcrumbsItem = ({ ...rest,match }) => ( <span> <li className={match.isExact ? 'breadcrumb-active' : undefined}> <Link to={match.url || ''}> {match.url} </Link> </li> <Route path={`${match.url}/:path`} component={BreadcrumbsItem} /> </span> )
reactjs – React Native(使用Redux)动画切换以编程方式
我需要的是不重新渲染整个组件,只是为了将Switch组件设置为正确的状态.
像这样的东西
<TouchableOpacity onPress={onPress}> <Text>{this.props.title}</Text> <Switch value={this.state.active}/> </TouchableOpacity>
任何的想法?
我发现这个非常常见的用例,我知道我会遇到很多类似的情况,所以我需要这种行为,但我在网上找不到任何示例或解决方案.也许我只是缺少一些东西.
谢谢
—编辑—
我也尝试过这个.我尝试使用shouldComponentUpdate禁用更新,我尝试仅在willRecieveProps中设置状态和/或切换,即使没有切换.我也试过玩LayoutAnimation.但没有任何作用. this.setState()只是不为Switch组件设置动画.
我也尝试过使用this._switch._rctSwitch.setNativeProps({value:nextProps.active}),但这也不起作用(因为_rctSwitch而闻起来).
class ViewWithSwitchInside extends React.Component { constructor(props) { super(props) this.toggle = this.toggle.bind(this); this.state = { active: props.active } } componentwillReceiveProps(nextProps) { if (this.state.active != nextProps.active) { this.setState({ active: nextProps.active }) } } toggle() { let newValue = !this.state.active this.setState({ active: newValue,}) if (typeof this.props.onClick === ''function'') { this.props.onClick(newValue) } } render() { return ( <TouchableWithoutFeedback onPress={this.toggle}> <View> <Text>{this.props.title}</Text> <Switch value={this.state.active} /> </View> </TouchableWithoutFeedback> ) } }
解决方法
我试图使用全局变量来设置切换器的值,我也阻止使用shouldComponentUpdate()重新呈现父组件,您可以在here上阅读更多内容
这是我的结果:
这是我的应用程序的初始状态.该全局变量设置为false,并且已经呈现了父组件.
现在我通过点击Switch周围的View来更改全局变量为true
但是没有任何东西在视觉上改变,只有变量改变了,而不是改变者.
然后我按下屏幕底部的“重新渲染”文本来更改状态(对Switch组件的无关更改),这种情况发生了:
这是上面App的代码:
var isActive = false; //global variable class Test extends Component { constructor(props) { super(props); this.state={active:false,irrelevantState: true}; } test(foo){ console.log("Attempting to change",foo); isActive = foo; } shouldComponentUpdate(nextProps,nextState){ if(this.state.active != nextState.active){//If the new state is different than the prevIoUs,stop rendering. this.test(nextState.active); return false; }else { //else,re-render everything return true; } } render(){ console.log("Test re-render"); return( <View style={{flex:1}}> <TouchableOpacity onPress={()=>{this.setState({active:!this.state.active})}} style={{flex:1,marginTop:20}}> <Text>Test Component</Text> <Switch value={isActive}/> </TouchableOpacity> <TouchableOpacity onPress={()=>{this.setState({active:true})}} style={{flex:1,marginTop:20}}> <Text>Test Component</Text> <Switch value={isActive}/> </TouchableOpacity> <TouchableOpacity style={{height:20}} onPress={()=>this.setState({irrelevantState:false})}> <Text> Re-render</Text> </TouchableOpacity> </View> ) } }
最好的办法是找到一种智能的方法来重新渲染,只有当你的应用程序的this.state.active和其他所需状态发生变化时,忽略其他变化.
今天关于使用React Router V4以编程方式导航和react router教程的分享就到这里,希望大家有所收获,若想了解更多关于javascript – 如何以编程方式从React Router 4.0中的事件处理程序导航到路由?、react-router – 使用React-Semantic-UI CardGroups配置React Router SubRoutes、react-router-v4 – 如何创建react-router v4 breadcrumbs?、reactjs – React Native(使用Redux)动画切换以编程方式等相关知识,可以在本站进行查询。
本文标签: