简体   繁体   中英

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:

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); and use the id from the prop inside my component.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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