React踩坑记

时间:2023-03-09 06:39:02
React踩坑记

一: Support for the experimental syntax 'classProperties' isn't currently enabled

ERROR in ./src/index.js

Module build failed (from ./node_modules/_babel-loader@8.0.5@babel-loader/lib/index.js):

SyntaxError: F:\Front-end items\vs code\react-2\src\index.js: Support for the experimental syntax 'classProperties' isn't currently enabled (7:15):

解决方法:cnpm i -D @babel/plugin-proposal-class-properties,并在.babelrc文件里添加:"plugins": ["@babel/plugin-proposal-class-properties"]

二: ES6 class 语法来定义一个组件的时候,this 的绑定

类的方法默认是不会绑定 this 的,因此如果我们没有绑定this,当调用这个方法时,this 的值会是 undefined。解决方法有三个:1,在构造函数中使用bind绑定this或在回调函数中使用bind绑定this;2,使用属性初始化器语法来正确的绑定回调函数;3,在回调函数中使用箭头函数。例子见官网,这几种都有介绍。

三:react-router-dom 中 path 在匹配路由组件时,exact表示严格匹配,即/about/是不匹配的。

例如:

function AppRouter() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
</nav> <Route path="/" exact component={Index}></Route>
<Route path="/about" component={About}></Route>
<Route path="/users" component={Users}></Route>
</div>
</Router>
)
}