Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

reactjs - React Hook "useState" is called in function that is neither a React function | Typescript

I'm having the problem with calling useState hook in my component. Everything is working fine. I can define props on Container as well as on Continer.Element.

But when I'm trying to call Hooks inside Container.Element - I'm getting an error.

const Container: React.FC<Props> & {Element: React.FC<ElementProps>} = () => {
  return <Container.Element />
}

Container.Element = () => {
  const [state, setState] = useState();
  return <div>Some JSX code</div>
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your code, Container is a valid React component but not the Container.Element.

When you do Container.Element = () => {};: You are just declaring a js function that return some jsx called Element.

To use react hooks, you have to follow the rules of hooks :D

From the react docs :

Only Call Hooks at the Top Level
Don’t call Hooks inside loops, conditions, or nested functions. 
Instead, always use Hooks at the top level of your React function. 
By following this rule, you ensure that Hooks are called 
in the same order each time a component renders. 

That’s what allows React to correctly preserve the state 
of Hooks between multiple useState and useEffect calls. 
(If you’re curious, we’ll explain this in depth below.)

Only Call Hooks from React Functions
Don’t call Hooks from regular JavaScript functions. Instead, you can:

? Call Hooks from React function components.
? Call Hooks from custom Hooks (we’ll learn about them on the next page).
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.

If you need to use hook in your example, you will have to use it in the Container component.

const Container: React.FC<Props> & {Element: React.FC<ElementProps>} = () => {
  const [state, setState] = useState();

  return <Container.Element />
}

Container.Element = () => {
  return <div>Some JSX code</div>
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...