简体   繁体   English

我应该导入 useState 和 useEffect 还是可以使用 React.useState 和 React.useEffect?

[英]Should I import useState and useEffect or is it ok to use React.useState and React.useEffect?

When using hooks for state, effect, context, etc, I do this:当为状态、效果、上下文等使用钩子时,我这样做:

import React, { useState, useEffect, useContext } from 'react';

However, I noticed that the following works just fine:但是,我注意到以下工作正常:

import React from 'react';

const App = () => {
  const [counter, setCounter] = React.useState();

  React.useEffect(() => console.log('hello!'), []);
}

My question is, is there any difference between those two?我的问题是,这两者之间有什么区别吗? Maybe when it comes to bundle size, or is Webpack smart enough to handle that?也许涉及到包的大小,或者 Webpack 是否足够聪明来处理这个问题?

Otherwise, is that bad practice?否则,这是不好的做法吗? Which approach do you use, and why?您使用哪种方法,为什么?

its better to use import {useState } from 'react' just because of readability , less typing and clean coding .最好使用import {useState } from 'react'只是因为可读性,更少的输入和干净的编码。 it doesn't matter in performance and bundle size性能和包大小无关紧要

两者都是一样的, import {useState } from 'react'不那么冗长,易于阅读和维护。

This thing is called destructuring in JS. 这件事在JS中称为解构 You can specify what fields of an object do you need to spread in separate variables: 您可以指定对象的哪些字段需要散布在单独的变量中:

const PI = Math.PI.

is the same as 是相同的

const {PI} = Math;

Which means, that here you import several fields of React object: 这意味着,这里您将导入React对象的几个字段:

import { useState, useEffect, useContext } from 'react'

I suggest you to use destructing, since this way you import only the parts of the object that you need. 我建议您使用析构,因为这样您就可以仅导入所需对象的各个部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM