我是新来对钩子做出反应的人。我正在为我的项目之一使用react-hook。我使用的是 hookrouter 软件包,但我尝试搜索该问题,但没有太大帮助。
我想要什么?
我正在尝试通过钩子路线传递道具以做出反应。例如,我想通过useRoutes(routes)
传递对象。
任何帮助将不胜感激。预先感谢!
答案 0 :(得分:1)
首先:
router.js
import React from "react";
import Users from "./components/Users";
import Contact from "./components/Contact";
import About from "./components/About";
const routes = {
"/": () => <Users />,
"/about": () => <About />,
"/contact": () => <Contact />
};
export default routes;
然后:
App / index.js
import {useRoutes} from 'hookrouter';
import Routes from './router'
function App() {
const routeResult = useRoutes(Routes)
return routeResult
}
有关更多信息,请在这里阅读-https://blog.logrocket.com/how-react-hooks-can-replace-react-router/
答案 1 :(得分:1)
实际上,我很困惑,并且在考虑通过props
传递useRoutes
而不是在routes
中单独传递组件。 Doc
const routes = {
'/': () => <HomePage />,
'/about': () => <AboutPage props={yourProps} />,
'/products': () => <ProductOverview props={yourProps} />,
'/products/:id': ({id}) => <ProductDetails id={id} />
};
const MyApp = () => {
const routeResult = useRoutes(routes);
return routeResult || <NotFoundPage />;
}
答案 2 :(得分:0)
我一直在做这样的事情:
RoutePropsContext.js
import React from 'react';
const RoutePropsContext = React.createContext(null);
export default RoutePropsContext;
index.js
import React from 'react';
import { BrowserRouter as Router} from 'react-router-dom';
ReactDOM.render(
<Router>
<App/>
</Router>
,document.getElementById('root')
);
App.js
import React from 'react';
import {withRouter} from 'react-router-dom';
import RoutePropsContext from '@helpers/context/RoutePropsContext';
function App(props) {
const routeProps = {
match: props.match,
location: props.location,
history: props.history
};
return(
<RoutePropsContext.Provider value={routeProps}>
<YourApp/>
</RoutePropsContext.Provider>
);
}
export default withRouter(App);
useRouteProps.js
import {useContext} from 'react';
import RoutePropsContext from '../context/RoutePropsContext';
function useRouteProps() {
const routeProps = useContext(RoutePropsContext);
return ({
...routeProps
});
}
export default useRouteProps;
Component_Using_the_Hook.js
import React from 'react';
import useRouteProps from './hooks/useRouteProps';
function SomeComponent() {
const {match, location, history} = useRouteProps();
return(
<Something/>
);
}
export default SomeComponent;