In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the knowledge of "how to use React high-level components to achieve a breadcrumb navigation". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What are react high-level components
React high-order components wrap the react components that need to be modified in the way of high-order functions, and return the react components after processing. React high-level components are frequently used in react ecology, such as withrouter in react-router and connect in react-redux. Many api are implemented in this way.
Benefits of using react advanced components
In our work, we often have a lot of page requirements with similar functions and repeated component code. usually we can achieve the function by completely copying the code, but the maintainability of the page will become very poor. changes need to be made to the same components on each page. Therefore, we can extract the common parts, such as accepting the same query operation results and the same tag package outside the component, and do a separate function, and pass in different business components as subcomponent parameters. This function does not modify the subcomponent, but wraps the subcomponent in the container component by combination, which is a pure function with no side effects. Thus we can decouple this part of the code without changing the logic of these components and improve the maintainability of the code.
Implement a high-level component on your own
Breadcrumb navigation with links is very common in front-end projects, but since breadcrumb navigation needs to manually maintain an array of all directory paths mapped to directory names, and all the data here can be obtained from the routing table of react-router, we can start from here to implement a high-level component of breadcrumb navigation.
First, let's look at the data provided by our routing table and the data required by the target breadcrumb component:
/ / what is shown here is react-router4 's route example let routes = [{breadcrumb: 'first-level directory', path:'/ a directory, component: require ('.. / a _ index.js'). Default, items: [{breadcrumb: 'second-level directory', path:'/ a _ breadcrumb _ index.js'), component: require ('. / a _ Universe _ index.js'). Default Items: [{breadcrumb: 'third-level directory 1Qing, path:' / a path path: / a path bUnip c2', component: require ('. / a-Uniqqb-c1max index.js'). Default, exact: true,}, {breadcrumb: 'tertiary directory-2, path: / / a-Unip bUnip c2' Component: component: require ('.. / a breadcrumb bqpxx.js'). Default, exact: true,},}]}] / / ideal breadcrumb assembly / / display format is a/b/ C1 with link const breadcrumbscomponent = ({breadcrumbs}) = > ({breadcrumbs.map ((breadcrumb, index) = > ({breadcrumb} {index))
< breadcrumbs.length - 1 && / } ))} ); 这里我们可以看到,面包屑组件需要提供的数据一共有三种,一种是当前页面的路径,一种是面包屑所带的文字,一种是该面包屑的导航链接指向。 其中第一种我们可以通过 react-router 提供的 withrouter 高阶组件包裹,可使子组件获取到当前页面的 location 属性,从而获取页面路径。 后两种需要我们对 routes 进行操作,首先将 routes 提供的数据扁平化成面包屑导航需要的格式,我们可以使用一个函数来实现它。 /** * 以递归的方式展平react router数组 */const flattenroutes = arr =>Arr.reduce (function (prev, item) {prev.push (item); return prev.concat (array.isarray (item.items)? Flattenroutes (item.items): item);}, [])
After that, the flattened directory path mapping is put into the processing function together with the current page path to generate the bread crumb navigation structure.
Export const getbreadcrumbs = ({flattenroutes, location}) = > {/ / initialize the matching array match let matches = []; location.pathname / / gets the path name, and then splits the path into each routing part. .split ('?') [0] .split ('/') / a reduce that calls `split () `once for each part. .reduce ((prev, cursection) = > {/ / merge the last routing part with the current part. For example, when the path is `/ x/xx/ xxx`, pathsection checks the match of` / x`` / xxx`` / x/xx/ xxx` and generates bread crumbs const pathsection = `${prev} / ${cursection}`; const breadcrumb = getbreadcrumb ({flattenroutes, cursection, pathsection,}) / / Import breadcrumbs into matches.push (breadcrumb) in the matches array; / / pass part of the path to the next reduce return pathsection;}); return matches;}
Then for each part of the breadcrumb path, the directory name is generated and a link attribute to the corresponding route location is attached.
Const getbreadcrumb = ({flattenroutes, cursection, pathsection}) = > {const matchroute = flattenroutes.find (ele = > {const {breadcrumb, path} = ele; if (! breadcrumb | |! path) {throw new error ('every route in router must contain `path` and `breadcrumb` attributes');} / find whether there is an attribute that matches / / exact is react router4, which is used to match the routing return matchpath (pathsection, {path, exact: true});}) / / returns the value of breadcrumb, and returns the original matching subpath name if (matchroute) {return render ({content: matchroute.breadcrumb | | cursection, path: matchroute.path,});} / / the default name of the path / / root directory that does not exist in the routes table is the first page. Return render ({content: pathsection = ='/'? 'Home': cursection, path: pathsection,});}
The final single bread crumb navigation style is then generated by the render function. A single breadcrumb component needs to provide the render function with the path path that the breadcrumb points to, and the two props of the breadcrumb content mapping content.
/ * * * / const render = ({content, path}) = > {const componentprops = {path}; if (typeof content = 'function') {return;} return {content};}
With these functions, we can implement a react high-level component that can pass in the current path and routing properties for the package component. Pass in a component and return a new same component structure so that it does not damage any functions and operations outside the component.
Const breadcrumbshoc = (location = _ window.location, routes = []) = > component = > {const breadcomponent = (); return breadcomponent;}; export default breadcrumbshoc
The method of invoking this high-level component is also very simple, simply passing in the current path and the routes property generated by the entire react router.
As for how to get the current path, we can use the withrouter function provided by react router. Please consult the relevant documentation on how to use it.
It is worth mentioning that the withrouter itself is a high-level component that provides several routing properties, including the location attribute, for the package component. So this api can also be used as a good reference for learning high-level components.
Withrouter (({location}) = > breadcrumbshoc (location, routes) (breadcrumbscomponent))
Qpraga
If the routes generated by react router is not manually maintained or even exists locally, but is pulled by request and stored in redux, when it is packaged through the connect high-order function provided by react-redux, the breadcrumb component will not be updated when the route changes. The method of use is as follows:
Function mapstatetoprops (state) {return {routes: state.routes,};} connect (mapstatetoprops) (withrouter (({location}) = > breadcrumbshoc (location, routes) (breadcrumbscomponent)
This is actually a bug of the connect function. Because the connect high-level component of react-redux implements the hook function shouldcomponentupdate for the incoming parameter component, the update-related lifecycle function (including render) is triggered only when the prop changes, and it is obvious that our location object is not passed into the parameter component as prop.
The officially recommended practice is to use withrouter to wrap connect's return value, that is,
Withrouter (connect (mapstatetoprops) (({location, routes})) = > breadcrumbshoc (location, routes) (breadcrumbscomponent)); "how to use React high-level components to achieve a breadcrumb navigation" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.