简体   繁体   中英

Understanding the syntax of connect() function in react-redux

I have seen that in order to connect a child component inside <Provider> to the redux store, we use connect() function. It is usually written as:

const mapStateToProps = (state) => {
    return {name: state}
}

export default connect(mapStateToProps)(Name) //'Name' is the component's name.

But I am failing to understand the syntax here. Here mapStateToProps() requires a state argument. But When we pass mapStateToProps to the connect() function, we are not passing any state to it. Also what is the use of (Name) just after connect() ? How is this syntactically correct?

As far as the "weird" looking syntax goes, just imagine a function that returns another function:

function add(x) {
    return function (y) {
        return x + y;
    };
}

Here if you call the add function and pass the x argument it'll return the inner function:

let inner = add(10);

And now you can call the inner function itself and pass the y argument

let result = inner(11);

And result is going to be equal to 21.

The shorter way to write it is to just chain the two calls together:

let result = add(10)(11);

Hope that makes some sense.

a simplified answer would be this: when you pass the mapStateToProps function to connect , somewhere in the connect method its calling the mapStateToProps that you passed to it and its giving it the state so you don't have to worry about it.

the second part is the weird sytax, basically the connect function returns another function that you invoke and pass it the component in this case Name .

Connect returns a Higher Order Component, which is basically a component wrapped with some extra functionality. When you create the HOC, you first create the wrapper (using whatever logic you wish to share among components) which then takes a new argument (the Component name you are wrapping). So think of it like this:

const wrapper = connect(mapStateToProps); const HOC = wrapper(Name);

Connect also takes care of passing the redux store to mapStateToProps as the state argument. If you do not want your component to listen to the store, but want it connected for some other reused logic that you have, you can call connect()(Name) , leaving the argument for mapStateToProps undefined . It wouldn't make sense for you to pass this local state into there because you already have access to the local state.

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