简体   繁体   English

这个 useSelector 函数如何返回状态?

[英]How does this useSelector function return state?

Sorry for this silly question but in one of the Redux videos I saw this function.抱歉这个愚蠢的问题,但在 Redux 视频之一中,我看到了这个功能。

const counter = useSelector(state => state.counter)

So, to my understanding how functions work is that you pass in something as the argument and it returns something but here inside useSelector we are getting access to state by passing it as an argument and then accessing it's variables(counter) further?所以,据我所知,函数是如何工作的,你传入一些东西作为参数,它返回一些东西,但在 useSelector 内部,我们通过将它作为参数传递然后进一步访问它的变量(计数器)来访问状态? How does this work?这是如何运作的? Am I missing some Javascript fundamental?我是否缺少一些 Javascript 基础知识?

state => state.counter

Can be expressed as可以表示为

function(state) { // state is just a parameter and can be any name
  return state.counter;
}

You can give it a name, and pass it instead.你可以给它一个名字,然后传递它。

function selectorFunction(state) {
  return state.counter;
}

useSelector(selectorFunction);

A callback function is one which will be called at a certain point in time by the parent function.回调函数是在某个时间点被父函数调用的函数。 We pass a callback function to the useSelector hook.我们将回调函数传递给useSelector钩子。 This function is called the selector function .该函数称为选择器函数 The useSelector hook calls this selector function and passes the redux store you created as the first argument . useSelector钩子调用这个选择器函数并将您创建的 redux 存储作为第一个参数传递

You can check the source code on how your selector function is called.您可以查看有关如何调用选择器函数的源代码

...
const storeState = store.getState(); // this is your redux store
const newSelectedState = selector(storeState); // 'selector' is 'your' callback function passed to 'useSelector' hook. 
...

Just like event listener callback functions where the first argument is the event object, similarly selector callback function's first argument is the redux store.就像第一个参数是事件对象的事件侦听器回调函数一样,类似地,选择器回调函数的第一个参数是 redux 存储。

The variable name can be anything you like.变量名称可以是您喜欢的任何名称。 A more reasonable would be store instead of state更合理的是store而不是state

function selectorFunction(store) {
  return store.counter;
}

useSelector(selectorFunction);

This when repetitive becomes a bit long to type and hence, compact arrow function are better suited for callback functions.这在重复变得有点长输入时,因此紧凑的箭头函数更适合回调函数。

useSelector((store) => store.counter);

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

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