简体   繁体   中英

react-redux useSelector hook disallows passing props directly to the selector

I've just started playing with the new useSelector hook provided in react-redux .

I have always passed props directly in to my selectors like this:

mapStateToProps(state, ownProps) {
   return {
      user: userSelector(state, ownProps.userId)
   }
}

Is passing props directly into selectors considered an anti pattern?

If "No", then how can I achieve this with useSelector ?

If "Yes", then what are the correct patterns to achieve this parameterisation of the selector?

This is good practice to use props in selectors.

The selector function does not receive an ownProps argument. However, props can be used through closure (see the examples below) or by using a curried selector.

useSelector accepts function with state argument. If you'll pass arrow function to useSelector you'll be able to access any variable in closure, including props .

This example is taken from official documentation

import React from 'react'
import { useSelector } from 'react-redux'

export const TodoListItem = props => {
  const todo = useSelector(state => state.todos[props.id])
  return <div>{todo.text}</div>
}

Also take a look at stale props page in official documentation on how to avoid some mistakes with local props usage.

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