简体   繁体   English

您是否能够将React钩子const命名为已经定义的const?

[英]Are you able to name a React hook const the same as an already defined const?

I'm trying to assign my Provider store prop to my Routes hook store, but I'm also creating a store in the function, so I have an issue with duplicated variables. 我试图将我的提供程序存储道具分配给我的Routes挂钩存储,但是我也在函数中创建一个存储,所以我遇到了重复变量的问题。 Is there a way to declare a hook with the same const name as an already defined const? 有没有办法用与已定义的const相同的const名称声明一个钩子?

  const store = createStore(reducers, applyMiddleware(thunk));
  sessionService.initSessionService(store);
  store.subscribe(() => {
    console.log('store.getState()', store.getState());
  });
  const [store] = useState();
  return (
    <Provider store={store}>
      <BrowserRouter className="router">

defining const [store] = useState(); 定义const [store] = useState(); throws an error of: Identifier 'store' has already been declared. 引发错误:标识符'store'已经被声明。

You are able to define a state in a Class, and have it have the same identifier as a const, but are we not able to do that using hooks? 您可以在Class中定义一个状态,并使它具有与const相同的标识符,但是我们不能使用钩子来做到这一点吗? Thanks for the help 谢谢您的帮助

由于它们是同一功能的一部分,因此它们位于相同的名称空间中,因此不能,您不能使用相同的名称命名它们。

If they both declared on the same block ( {} ) then no, because const (and let ) is block scoped . 如果它们都在同一块( {} )上声明,则不会,因为const (和let )是块作用域的

If they "live" on a different block though, its fine: 如果他们“生活”在另一个街区,那就好了:

 function foo() { { const x = 1; } const x = 2 console.log('x is ', x) } foo() 

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

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