So sánh this.props.router.push và window.location.href năm 2024
I expect that you have read my previous blog, so you already know what is the three route props. If you don't know about it, check my previous blog here. I discuss how we can pass the three route props, and I want to show you another easy way to access it without thinking to pass as props. useHistoryBasically, this hook gives you access to
Enter fullscreen mode Exit fullscreen mode What's inside history?Okay... so many things here. I know it is confusing in the beginning. I will explain the most common uses of these attributes.
Enter fullscreen mode Exit fullscreen mode I have never utilized the state before. However, after I read the documentation, the documentation gave me an idea. For example, if you want to know where the user came from, you can utilize the state.
I have never used the three go function, but I just want to let you know that this function has existed in history I also prepare codesandbox to help you understand. useLocationBriefly, this is like a state that always returns your current URL. If the URL is changed, the useLocation will be updated as well. What's inside location?useLocation doesn't have any function like useHistory, and it is just to grab information about your current URL. I will use the previous link that we tried to use
2 from history in the example
3. from that URL, if we are trying to call useLocation, we will get this object. Just keep in mind the purpose
4 is getting information from the current route, and it will return these attributes.
Enter fullscreen mode Exit fullscreen mode useParamsThis is the easiest hook from react-router to understand. Whenever you call this hook you will get an object that stores all the parameters as attributes. You just need this line of code and you can have access to your params.
Enter fullscreen mode Exit fullscreen mode you can play around in my CodeSandBox ConclusionI hope this post could help you to understand the three main useful hooks from react-router. It is confusing in the beginning, but after I play around with it, everything makes sense and understandable. Enjoy playing react-router! post your comments to ask me questions. |