Javascript 反应链接与标签和箭头功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43087007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
react link vs a tag and arrow function
提问by forJ
Hi guys I'm a beginner programmer just started on react router.
大家好,我是一名初学者程序员,刚刚开始使用 React 路由器。
I have two questions. What is the difference between using <Link to="/page">and <a href="page">? Both make the exact same get request to /pagebut I get an error when I use <a href="page">but it works when I use <Link to="/page">when I am nesting routes. I don't understand how there could be any difference when I know for fact that both render to exact same url
我有两个问题。using<Link to="/page">和 和有<a href="page">什么不一样?两者都发出完全相同的 get 请求,/page但我在使用时收到错误,<a href="page">但<Link to="/page">在我嵌套路由时使用它时有效。当我知道两者都渲染到完全相同的 url 时,我不明白怎么会有任何区别
Second is the weird arrow function in react router v4 documentation
其次是 react router v4 文档中的奇怪箭头函数
const About = () => (
<div>
<h2>About</h2>
</div>
)
I know () => {}these are new in ES6 but I cannot find anything on normal brackets instead of parentheses. What are they?
我知道() => {}这些是 ES6 中的新内容,但我在普通括号而不是圆括号中找不到任何内容。这些是什么?
Edit
编辑
My index.js class (I have all the imports)
我的 index.js 类(我有所有的导入)
render((
<Router>
<div>
<Route component={App}/>
</div>
</Router>
), document.getElementById('root')
);
My App.js class
我的 App.js 类
class App extends Component {
render() {
return (
<div className="container">
<header>
<span className="icn-logo"><i className="material-icons">code</i></span>
<ul className="main-nav">
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/teachers">Teachers</Link></li>
<li><Link to="/courses">Courses</Link></li>
</ul>
</header>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/teachers" component={Teachers}/>
<Route path="/courses" component={Course}/>
</div>
);
}
}
export default App;
The error I'm getting.
Cannot GET /abouton the browser when I try to move to localhost:8080/about. However, when I click the aboutbutton, it goes to exactly the same url /aboutand renders perfectly
我得到的错误。
Cannot GET /about当我尝试移至localhost:8080/about. 但是,当我单击about按钮时,它会转到完全相同的网址/about并完美呈现
回答by flash
This may be a bit late to address your issue and you may well have figured it out. But here's my take:
解决您的问题可能有点晚了,您可能已经想通了。但这是我的看法:
First:
第一的:
What is the difference between using
<Link to="/page">and<a href="page">
使用
<Link to="/page">和 有什么区别<a href="page">
- On the surface, you seem to be comparing apples and oranges here. The path in your anchor tag is a relative path while that one in the
Linkis absolute (rightly so, I don't thinkreact-routersupports relative paths yet). The problem this creates is say you are on/blah, while clicking on yourLinkwill go to/page, clicking on the<a href='page' />will take you to/blah/page. This may not be an issue though since you confirmed the correctness of the url, but thought to note. - A bit deeper difference, which is just an addon to @Dennis answer (and the docs he pointed to), is when you are already in a route that matches what the
Linkpoints to. Say we are currently on/pageand theLinkpoints to/pageor even/page/:id, this won't trigger a full page refresh while an<a />tag naturally will. See issue on Github.
- 从表面上看,您似乎是在比较苹果和橙子。锚标记中的路径是相对路径,而 中的路径
Link是绝对路径(没错,我认为react-router尚不支持相对路径)。这造成的问题是说你在/blah,点击你的Link将去/page,点击<a href='page' />将带你到/blah/page。这可能不是问题,因为您确认了 url 的正确性,但认为要注意。 - 一个更深层次的区别,这只是@Dennis 答案(以及他指向的文档)的一个插件,是当您已经处于与
Link指向的内容匹配的路线中时。假设我们当前处于 on/page并且Link指向/page甚至/page/:id,这不会触发整页刷新,而<a />标签自然会触发。请参阅Github 上的问题。
A fix I used to solve my little need around this was to pass in a stateproperty into link like so <Link to={{pathname: "/page", state: "desiredState"}}>Page</Link>. Then I can check for this in the target component's (say <Page />) componentWillReceivePropslike so:
我用来解决我对此的小需求的修复方法是将state属性传递到链接中,如下所示<Link to={{pathname: "/page", state: "desiredState"}}>Page</Link>。然后我可以像这样在目标组件的(比如<Page />)中检查这个componentWillReceiveProps:
componentWillReceiveProps(nextProps){
if (nextProps.location.state === 'desiredState') {
// do stuffs
}
}
Second question:
第二个问题:
the weird arrow function in react router v4 documentation... I cannot find anything on normal brackets instead of parentheses. What are they?
反应路由器 v4 文档中的奇怪箭头函数......我在普通括号而不是括号上找不到任何东西。这些是什么?
Arrow functions; again @Dennis and @Jaromanda X have kind of addressed it. However, I've got three bits to add:
箭头函数;@Dennis 和 @Jaromanda X 再次解决了这个问题。但是,我要补充三点:
- When you have
() => blahwithout the curly braces{}, you are implicitly returning whatever follows the=>in this caseblah. But when you have curly braces immediately after the arrow, then it's now your responsibility toreturnsomething if you so desire. So() => blah(which by the way is synonymous to() => (blah)) will be more similar to() => { return blah }and not() => { blah }. - So what happens if you want to return an object:
{ blah: blah }; this is what @Jaromanda X was pointing at. You will then need to do() => ({ blah: blah })or simply() => ({ blah })for implicit return or you could return explicitly like so() => { return { blah: blah } }. - My third bit is to point you to MDN
- 当您
() => blah没有花括号时{},=>在这种情况下,您将隐式返回 后面的任何内容blah。但是,当您在箭头后立即使用花括号时,return如果您愿意,现在就应该对某些事情负责。因此() => blah(顺便说一下,它是 的同义词() => (blah))将更类似于() => { return blah }而不是() => { blah }。 - 所以,如果你想返回一个对象会发生什么:
{ blah: blah }; 这就是@Jaromanda X 所指的。然后,您将需要执行() => ({ blah: blah })或仅() => ({ blah })用于隐式返回,或者您可以像这样显式返回() => { return { blah: blah } }。 - 我的第三点是将你指向MDN
Hope it helps.
希望能帮助到你。
回答by Dennis
The component allows you to do more than the normal link element. For instance, because it's a React component you have the benefits of having a state and what not (if you want that). You can see more documentation on here. Without the error I'm not sure what happens, but I suspect the routing library wants you to use the component, over a normal html element.
该组件允许您做比普通链接元素更多的事情。例如,因为它是一个 React 组件,所以你有一个状态和什么没有的好处(如果你想要的话)。您可以在此处查看更多文档 。如果没有错误,我不确定会发生什么,但我怀疑路由库希望您通过普通的 html 元素使用该组件。
With regards to () => {}this is a construct which is called an anonymous function, or a lambda expression. It's basically the same as saving a function in a variable: var x = function(){ return (<div>...) };if you have anything in the first parenthesis, it's a parameter which you have access to: const x = (y) => return y*2;The reason it's done in React is to expose the function scope to the component it lies in.
与() => {}此相关的是一种称为匿名函数或 lambda 表达式的构造。这与将函数保存在变量中基本相同:var x = function(){ return (<div>...) };如果您在第一个括号中有任何内容,则它是您可以访问的参数:const x = (y) => return y*2;在 React 中这样做的原因是将函数作用域暴露给它所在的组件。
回答by Mohamed Allal
There is no better then looking at the code source.
没有比查看代码源更好的方法了。
https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js
https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js
You can see that Linkis a component, that internally use history. Which is the module||library behind the history and navigation for react-router. And come with different modes (in memory history, browserHistory, hashHistory. And even custom).
您可以看到这Link是一个内部使用history的组件。这是反应路由器历史和导航背后的模块||库。并带有不同的模式(内存历史、浏览器历史、哈希历史。甚至自定义)。
Yea as a similarity it render an anchor tag but the default behavior is overridden (preventDefault()). They could have used just a div. But not completely right. As for the reason bellow.
是的,作为相似之处,它呈现一个锚标记,但默认行为被覆盖(preventDefault())。他们本可以只使用一个 div。但并不完全正确。至于原因如下。
So basically it work like that:
所以基本上它是这样工作的:
Observe the condition bellow
观察以下情况
if (
!event.defaultPrevented && // onClick prevented default
event.button === 0 && // ignore everything but left clicks
(!this.props.target || this.props.target === "_self") && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) // ignore clicks with modifier keys
) {
}
if the condition above is met. It will use history(push or replace). Otherwise it will leave the browser normal behavior. And so in that case it will be just a normal anchor tag <a />. Example letting the browser handle target='blank'. The condition are well explained.
Then depending on the type of history object. The behavior change. Not the behavior of ` itself. But just the result of the history object type.
如果满足上述条件。它将使用历史记录(推送或替换)。否则它将使浏览器保持正常行为。所以在这种情况下,它将只是一个普通的锚标签<a />。让浏览器处理 target='blank' 的示例。条件得到了很好的解释。然后取决于历史对象的类型。行为改变。不是`本身的行为。但只是历史对象类型的结果。
In resume:
在简历中:
<Link />is a component, that render a <a />anchor tag. However in the main conditions the default behavior is prevented (preventDefault()). That allow it to apply the change to the history object (onClickevent). Which react-router navigation is based on. And on the some conditions as mentioned above. It just fall back to the browser behavior. And just be exactly a <a />?anchor tag (no preventDefault()).
<Link />是一个组件,它呈现一个<a />锚标记。然而,在主要条件下,默认行为被阻止 ( preventDefault())。这允许它将更改应用于历史对象(onClick事件)。哪个反应路由器导航基于。并且在上面提到的一些条件下。它只是回到浏览器行为。并且只是一个<a />? 锚标签(没有preventDefault())。
For the use. If you are using React-router. Then you just need to use Link.
为使用。如果您使用的是 React-router。然后你只需要使用Link.
回答by mohamed amine salah
The href attribute would trigger a page refresh which would reset the application states. However the link and navlink of react-router doesn't trigger a page refresh. Since React is used to create single page applications most of the time make sure you choose Link or Navlink when working with routing
href 属性会触发页面刷新,从而重置应用程序状态。但是 react-router 的 link 和 navlink 不会触发页面刷新。由于 React 大部分时间用于创建单页应用程序,因此在处理路由时请确保选择 Link 或 Navlink

