简体   繁体   中英

What does “Stateless function components cannot be given refs” mean?

I have this:

const ProjectsSummaryLayout = ({projects}) => {
   return (
      <div className="projects-summary col-md-10">
          <h3>Projects</h3>
          <ul>
              { projects.map(p => <li key={p.id}>{p.contract.client}</li>) }
          </ul>
      </div>
   )
}

const ProjectsSummary = connect(
   state => ({projects: state.projects})
)(ProjectsSummaryLayout)

and I get:

Warning: Stateless function components cannot be given refs (See ref "wrappedInstance" in ProjectsSummaryLayout created by Connect(ProjectsSummaryLayout)). Attempts to access this ref will fail.

What is it trying to tell me? Am I actually doing something wrong?

I see discussion about this here but unfortunately I simply don't understand the conclusion.

In React, refs may not be attached to a stateless component .

React Redux 3 attaches a ref to the component you give it regardless of whether or not it's stateless. The warning you see comes from React because internally, React Redux 3 attaches a ref to the stateless component you supplied ( ProjectsSummaryLayout ).

You're not doing anything wrong and according to this GitHub comment , you can safely ignore the warning.

In React Redux 4 , no ref is attached to the wrapped component by default, which means if you upgrade to React Redux 4, the warning should go away.

React has 2 commonly used component styles.

  • Functional Component
  • Class Component

So, When I was making use of Functional one then I was encountering this error. 我使用功能组件时遇到错误

Code snippet corresponding to Functional Component

方形组件的代码

But as soon as I changed it to Class Component then it worked.

有效

Code snippet corresponding to Class Component.

在此输入图像描述

Try changing Functional Component to Class Component. I hope it will resolve your problem.

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