简体   繁体   中英

React/prefer-stateless-function vs class decorators?

So, I am setting up a brand new React project, and have updated all my deps to the latest versions.

This caused some eslint breakages in the project, so I'm going through and correcting these.

I seem to have come across conflicting rules. React/prefer-stateless-function tries to tell me to write my component as a pure function, but if I do that, I can no longer use decorators to connect my component to my Redux store.

How are people getting around this? The component in question is a "dumb" component (eg only props, no state), so honestly it should be written as a pure function, but then I lose the ability to connect it to my store via @asyncConnect and @connect .

Class component with decorators:

@connect(
  state => ({ // eslint-disable-line
    user: state.publicData.user.data,
    error: state.publicData.user.error,
    loading: state.publicData.user.loading,
  }),
  { initializeWithKey })
export default class UserProfile extends Component {
  ...stuff
}

Pure function component:

// How can I use decorators?
export default function UserProfile(props) {
  ...stuff
}

Case of two decorators combined:

@asyncConnect([{
  deferred: true,
  promise: ({ params, store: { dispatch, getState } }) => {
    if (!isLoaded(getState())) {
      return dispatch(loadUser(params.userID))
    }
  },
}])
@connect(
  state => ({ // eslint-disable-line
    user: state.publicData.user.data,
    error: state.publicData.user.error,
    loading: state.publicData.user.loading,
  }),
  { initializeWithKey })
export default class UserProfile extends Component {
  ...stuff
}

Redux doesn't need decorators to work, connect is really just a function. You can use it like this:

export default connect(mapStateToProps)(props => <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