简体   繁体   English

react-redux useSelector hook不允许将props直接传递给选择器

[英]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 . 我刚刚开始使用react-redux提供的新useSelector挂钩。

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 ? 如果“否”,那么如何使用useSelector实现这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. 这是在选择器中使用props好习惯。

The selector function does not receive an ownProps argument. 选择器函数不接收ownProps参数。 However, props can be used through closure (see the examples below) or by using a curried selector. 但是,可以通过闭合(参见下面的示例)或使用curried选择器来使用道具。

useSelector accepts function with state argument. useSelector接受带有state参数的函数。 If you'll pass arrow function to useSelector you'll be able to access any variable in closure, including props . 如果你将arrow函数传递给useSelector你将能够访问闭包中的任何变量,包括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. 另请参阅官方文档中关于如何避免使用本地props一些错误的陈旧道具页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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