如题

react 函数调用的坑

1
2
3
4
5
render: item => (
<span title={item.opContent}>
{item.opContent.length > opContentMaxLength ? <span>item.opContent.substr(0, opContentMaxLength)&nbsp;&nbsp;<a onClick={this.handleModalVisible(true, item)}>查看</a></span> : item.opContent}
</span>
),

在页面加载时,每一条记录都会调用一次 this.handleModalVisible(true, item)
正确的应该是这样:

1
2
3
4
5
render: item => (
<span title={item.opContent}>
{item.opContent.length > opContentMaxLength ? <span>item.opContent.substr(0, opContentMaxLength)&nbsp;&nbsp;<a onClick={() => this.handleModalVisible(true, item)}>查看</a></span> : item.opContent}
</span>
),

npm 升级 package.json 依赖包到最新版本号

使用工具包:npm-check-updates

全局安装ncu:npm install -g npm-check-updates

使用

  • 检查package.json中dependencies的最新版本:ncu
  • 更新dependencies到新版本:ncu -u
    1
    2
    3
    4
    Hmmmmm... this is taking a long time. Your console is telling me to wait for input
    on stdin, but maybe that is not what you want.
    Try winpty ncu.cmd, or specify a package file explicitly with --packageFile package.json.
    See https://github.com/tjunnone/npm-check-updates/issues/136#issuecomment-155721102

指定 packageFile 文件名的方式会快一些

1
ncu -u --packageFile package.json

Google Chrome 不能在线安装 React 相关的插件,可下载离线版进行安装

由于众所周知的原因,Google Chrome 不能访问应用商店,所以,不能在线安装 React Developer Tools、Redux DevTools、JetBrains IDE Support,不过网上有离线版可供下载,地址如下:

crx4chrome官网,还可以搜索扩展。

安装方式

请参考像用 IDEA 调试 Java 代码一样,用 WebStorm 调试 react 代码,该文章有离线安装的详细讲解。

Redux DevTools 调试,版本不兼容问题

Google Chrome Version 70.0.3538.67 (Official Build) (64-bit)安装Redux DevTools 2.15.1的离线版,结果报了很多错,错误直指Redux源码。在没有安装该插件的浏览器上可以正常运行。

解决方式,安装最新版的Redux DevTools 2.16.5

WebStorm + React 项目,配置 ESLint

传送门

依赖包版本

package.json 这样定义 "eslint": "^5.6.0",cnpm i 之后,实际上安装的是当前最新版本 5.10.0,运行 · 的时候,会得到以下提示:

1
2
3
4
5
6
7
8
The react-scripts package provided by Create React App requires a dependency:

"eslint": "5.6.0"

Don't try to install it manually: your package manager does it automatically.
However, a different version of eslint was detected higher up in the tree:

C:\workspace\react\react-full-stack-learning\node_modules\eslint (version: 5.10.0)

解决办法是,把版本号前面的 ^ 去掉,这样会精确匹配。

关于版本号的定义,请自行百度。

npm start 时,指定启动端口

以指定 91 端口为例

  • windows

    1
    "start": "set PORT=91 && react-scripts start",
  • linux

    1
    "start": "export PORT=91 && react-scripts start",

macOS 下遇到的总是

npm start 之后,提示:

1
2
? Admin permissions are required to run a server on a port below 1024.
Would you like to run the app on another port instead? (Y/n)

这是因为非 root 用户,不允许在 1024 以下的端口运行项目。

解决

  • 想要在指定1024以下的端口运行,可以先 dudo -i 以 root 用户来运行 npm start。
    • 执行 sudo -i 之后,会默认进入 root 根目录,要启动项目,还需要 cd 到项目的根目录下。
  • 当然,不设置则用默认3000端口,或者设置为 1024 以上的端口最省事儿。

package.json 不能添加注释

  • node 项目的 package.json 添加注释会报错。
  • JSON 数据不支持注释,虽然某些解析器支持,但最好不要在 JSON 数据内容添加注释,否则遇到不支持的解析器,可能会花很多时间来找问题。