简体   繁体   English

可以将相同的参数名称用作函数 param 和 local 吗?

[英]can the same parameter name be used as function param and local?

I would like to create a function component - 'Task' , with parameter named id, and have this parameter saved in the state with the same name:我想创建一个函数组件 - 'Task' ,参数名为 id,并将此参数保存在具有相同名称的状态中:

const Task = ({ id,text }) => {
    const [id] = useState(id);    // ERROR: identifier 'id' has already been declared
        
    return ( <div/>);
}```

I'm using Task like this: 

```class App extends Component {
render() { 
    <Task id='123' text='TEXT' />
}```
 

You are already defining in the scope the variable name.您已经在范围内定义了变量名称。

const Task = ({ id:idParam, text }) => {
    const [id] = useState(idParam);    // Should suffice
        
    return ( <div/>);
}```
const Task = ({ id, text }) => {
  const [id] = useState(id);

  // ...
}

is equivalent to相当于

const Task = (params) => {
  let { id, text } = params
  const [id] = useState(id);

  // ...
}

which lead to redeclaration which produced error这导致重新声明产生错误

Instead, you could destruct with another variable相反,您可以使用另一个变量进行破坏

const Task = ({ id: passedId, text }) => {
  const [id] = useState(passedId);

  // ...
}

or just use one passed parameter或者只使用一个传递的参数

const Task = (params) => {
  const [id] = useState(params.id);

  // ...
}

Error aside, it looks like there's something wrong when we have to keep the prop in a state, I would probably skip the const [id] = useState(id);撇开错误不谈,当我们必须将道具保持在某种状态时,看起来好像出了点问题,我可能会跳过const [id] = useState(id); and use the id from the prop inside my component.并在我的组件内使用道具中的id

In case if id gets changed from the parent ( App ), then still the Task is referring to old value, just because initially we put the id in to state, and that state value not gonna change even if the prop gets changed如果id从父级 ( App ) 被更改,那么Task仍然引用旧值,只是因为最初我们将 id 置于 state 中,并且即使 prop 被更改,该状态值也不会改变

const Task = ({ id, text }) => 
    ....        
    return ( <div/>);
}

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

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