Redux hooks, useSelector and useDispatch that are better than connect

Those who have used redux know connect, but every time we use this, do we have to write a bunch of code?

as follows,

// const mapStateToProps = state => ({
    
    
//     banner: state.recommend.banner
// })
// const mapPropsToProp = dispatch => ({
    
    
//     getBanner: (url)=>{dispatch(getBannerAction(url))}
// // // })
// // export default connect(mapStateToProps,mapPropsToProp)(memo(MHDiscover))

And when exporting, you have to use connect package, which is particularly troublesome.

Recommend redux hook to realize our access to and modification of redux data more convenient,

Look at the code first
Insert picture description here

const dispatch = useDispatch();
  const recommend = useSelector(
    (state) => ({
    
    
      banner: state.recommend.banner,
    }),
    shallowEqual
  );

useSelector, similar to our mapStateToProps, is used to obtain state data, but it is more convenient and concise.
He passes in two parameters, the first is a function, as shown in the state, which returns an object, in which the data of redux can be obtained through the state. The second value is actually performance optimization, which is used to decide whether to re-render the component.
Every time you modify the data of redux, useSelector will compare the two objects before and after by default, such as {banner} in the figure. Although you have not modified this data, you will still return the new {banner}, then useSelector will compare these two objects. Compare each object, how to compare it, just directly ===, that is, the two objects are exactly the same, so there is no need to cause the re-rendering of the assembly.
You can see the source code.
Insert picture description here
By default, refEuqality is passed in. What is this,
Insert picture description here
simple and rude .
But we know that even if the two objects look the same, their heap addresses are not the same, so they are definitely not equal when they are compared. Then the role of the second parameter is born, and the shallowEqual provided to us by react-redux (A function for comparison is implemented in React. It is used to compare conncet objects to determine whether to re-render. Then react-redux also provides us with a similar function.) Pass shallowEquall as the second parameter Enter, useSelector will use this function to compare, this function is a shallow comparison (if you are interested, you can understand the source code), so useSelector is really useful.

useDispatch, as the name suggests, is used to dispatch action, this is just use, the effect is the same as conncet.

You can also get the entire Store object through useSotre.
const Store = useStore()

Guess you like

Origin blog.csdn.net/lin_fightin/article/details/112972873