使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
布局/BaseLayout.jsx
import { Outlet } from "react-router-dom";
import Navbar from "../components/Navbar";
const BaseLayout = () => {
return(
<div>
<Navbar/>
<Outlet/>
</div>
)
}
export default BaseLayout
路由器/index.jsx
import { createBrowserRouter} from "react-router-dom";
import BaseLayout from "../layouts/BaseLayout";
import HomePage from "../views/HomePage";
import Menu from "../components/Menu"
import Detail from "../components/Detail";
const router = createBrowserRouter([
{
element: <BaseLayout/>,
children:[
{
path: "/",
element: <Menu />,
},
{
path: '/:id',
element: <Detail/>
}
]
},
])
export default router
存储/actionType.js
export const FETCH_DATA_FOODS = "food/setFood"
export const FETCH_DATA_FOODS_DETAILS = "food/setDetailFood"
存储/还原器/还原器.js
import { FETCH_DATA_FOODS, FETCH_DATA_FOODS_DETAILS } from "../actionType";
const initialState = {
foods:[],
detailFood:{}
};
const foodReducer = (state = initialState, action) => {
switch(action.type){
case FETCH_DATA_FOODS:
return{
...state,
foods: action.payload
}
case FETCH_DATA_FOODS_DETAILS:
return{
...state,
detailFood: action.payload
}
default:
return state
}
}
export default foodReducer
存储/actionCreator
import { FETCH_DATA_FOODS, FETCH_DATA_FOODS_DETAILS } from "./actionType";
// import { FETCH_DATA_FOODS } from "../actionType";
export const actionFoodSetFoods = (payload) => {
return {
type: FETCH_DATA_FOODS,
payload,
};
};
export const actionDetailSetDetailFood = (payload) => {
return {
type: FETCH_DATA_FOODS_DETAILS,
payload,
};
};
export const fetchDataFoods = () => {
return (dispatch, getState) => {
fetch("https://maxxkafe.foxhub.space/users")
.then((response) => {
if (!response.ok) {
throw new Error("notOk");
}
return response.json();
})
.then((data) => {
// dispatcher({
// type: "food/setFood",
// payload: data
// })
dispatch(actionFoodSetFoods(data));
});
};
};
export const fetchDetailDataFood = (id) => {
return (dispatch, getState) => {
console.log(id);
fetch(`https://maxxkafe.foxhub.space/users/${id}`)
.then((response) => {
if (!response.ok) {
throw new Error("gaOkNich");
}
console.log(response, ",,,,,,,,");
return response.json();
})
.then((data) => {
dispatch(actionDetailSetDetailFood(data));
});
};
};
stores/index.js
import { legacy_createStore as createStore, combineReducers, applyMiddleware } from 'redux'
import foodReducer from './reducers/foodReducer'
import thunk from "redux-thunk"
const rootReducer = combineReducers({
foods: foodReducer
});
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store
应用程序.js
import { RouterProvider } from "react-router-dom";
import router from "./routers";
import { Provider } from "react-redux";
import store from "./stores";
const App = () => {
return (
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
);
};
export default App;
组件/类别.jsx
import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import { fetchDataCategories } from "../stores/actionCreate";
import RowCategory from "../views/rowTableCategory";
const Category = () => {
// const [categories, setCategories] = useState([])
const { categories } = useSelector((state) => state.categories);
const dispatcher = useDispatch();
useEffect(() => {
// fetch("http://localhost:3003/categories")
// .then((response) => {
// if(!response.ok){
// throw new Error ("gaOkNich")
// }
// return response.json()
// })
// .then((data) => {
// setCategories(data)
// })
dispatcher(fetchDataCategories());
}, []);
return (
<section className="mt-12">
<div className="flex mr-20 mb-4">
<Link to={'/add-Form'} className="flex ml-auto text-white bg-red-500 border-0 py-2 px-6 focus:outline-none hover:bg-red-600 rounded">
Create Category
</Link>
</div>
<div className="overflow-hidden rounded-lg border border-gray-200 shadow-md m-5">
<table className="w-full border-collapse bg-white text-left text-sm text-gray-500">
<thead className="bg-gray-50">
<tr>
<th scope="col" className="px-6 py-4 font-medium text-gray-900">
Name
</th>
<th scope="col" className="px-6 py-4 font-medium text-gray-900">
Created At
</th>
<th scope="col" className="px-6 py-4 font-medium text-gray-900">
Updated At
</th>
<th
scope="col"
className="px-6 py-4 font-medium text-gray-900"
></th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 border-t border-gray-100">
{categories.map((el) => {
return <RowCategory key={el.id} el={el} />;
})}
</tbody>
</table>
</div>
</section>
);
};
export default Category;
组件/login.jsx
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { fetchDataFoods, login } from "../stores/actionCreate";
const Login = () => {
const input = {
email: "",
password: "",
};
const [values, setValues] = useState(input);
// const [password, setPassword] = useState('')
// const {admin} = useSelector((state) => state.admin)
const dispatcher = useDispatch();
const movePage = useNavigate();
const handleChange = (event) => {
const { name, value } = event.target;
setValues({
...values,
[name]: value,
});
console.log(value);
};
const handleLogin = async (event) => {
event.preventDefault();
try {
await dispatcher(login(values));
await dispatcher(fetchDataFoods());
movePage("/home");
} catch (error) {
console.log(error);
}
};
return (
<section className="font-mono bg-white-400 mt-[10rem]">
<div className="container mx-auto">
<div className="flex justify-center px-6 my-12">
<div className="w-full xl:w-3/4 lg:w-11/12 flex justify-center">
<div className="w-full lg:w-7/12 bg-white p-5 rounded-lg lg:rounded-l-none">
<h3 className="pt-4 text-2xl text-center">Login Your Account!</h3>
<form
className="px-8 pt-6 pb-8 mb-4 bg-white rounded"
onSubmit={handleLogin}
>
<div className="mb-4">
<label
className="block mb-2 text-sm font-bold text-gray-700"
htmlFor="email"
>
Email
</label>
<input
className="w-full px-3 py-2 mb-3 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline"
id="email"
type="email"
name="email"
placeholder="Email"
// onChange={(event) => setValues({email: event.target.value})}
onChange={handleChange}
value={values.email.email}
/>
</div>
<div className="mb-4 md:flex md:justify-between">
<div className="mb-4 md:mr-2 md:mb-0">
<label
className="block mb-2 text-sm font-bold text-gray-700"
htmlFor="password"
>
Password
</label>
<input
className="w-full px-3 py-2 mb-3 text-sm leading-tight text-gray-700 border rounded shadow appearance-none focus:outline-none focus:shadow-outline"
id="password"
type="password"
name="password"
placeholder="Password"
onChange={handleChange}
value={values.password}
// onChange={(event) => setValues({password: event.target.value})}
/>
</div>
</div>
<div className="mb-4 md:flex md:justify-between"></div>
<div className="mb-6 text-center">
<button
className="w-full px-4 py-2 font-bold text-white bg-blue-500 rounded-full hover:bg-blue-700 focus:outline-none focus:shadow-outline"
type="submit"
>
Login
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
);
};
export default Login;
其他回答
只需使用this.props.history.push('/where/to/go');
上面已经提到,我们可以使用useNavigate()在上一次更新React Router V6(不包括useHistory)中导航
import { useNavigate } from 'react-router-dom';
const myComponent = () => {
const navigate = useNavigate();
navigate('my_url');
...
}
但我在这里找不到的是调用导航出React组件,就像将redux saga函数中的页面导航到另一个页面。以防万一,如果你有同样的问题,这是我发现的。
在根组件中(我称之为<App/>)
import { useNavigate } from 'react-router-dom';
import useBus from 'use-bus';
const App = () => {
const navigate = useNavigate();
useBus('@@ui/navigate', (action) => navigate(action.payload.url), []);
...
}
脱离React组件(在我的例子中是redux saga函数)
import { dispatch } from 'use-bus';
dispatch({ type: '@@ui/navigate', payload: { url: '/404' } });
希望有帮助!
对于ES6+React组件,以下解决方案适用于我。
我跟随费利佩·斯金纳,但添加了一个端到端解决方案,以帮助像我这样的初学者。
以下是我使用的版本:
“反应路由器”:“^2.7.0”“反应”:“^15.3.1”
下面是我的react组件,其中我使用react路由器进行编程导航:
import React from 'react';
class loginComp extends React.Component {
constructor( context) {
super(context);
this.state = {
uname: '',
pwd: ''
};
}
redirectToMainPage(){
this.context.router.replace('/home');
}
render(){
return <div>
// skipping html code
<button onClick={this.redirectToMainPage.bind(this)}>Redirect</button>
</div>;
}
};
loginComp.contextTypes = {
router: React.PropTypes.object.isRequired
}
module.exports = loginComp;
以下是路由器的配置:
import { Router, Route, IndexRedirect, browserHistory } from 'react-router'
render(<Router history={browserHistory}>
<Route path='/' component={ParentComp}>
<IndexRedirect to = "/login"/>
<Route path='/login' component={LoginComp}/>
<Route path='/home' component={HomeComp}/>
<Route path='/repair' component={RepairJobComp} />
<Route path='/service' component={ServiceJobComp} />
</Route>
</Router>, document.getElementById('root'));
警告:此答案仅涵盖1.0之前的ReactRouter版本之后,我将用1.0.0-rc1用例更新这个答案!
你也可以在没有混合的情况下这样做。
let Authentication = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
handleClick(e) {
e.preventDefault();
this.context.router.transitionTo('/');
},
render(){
return (<div onClick={this.handleClick}>Click me!</div>);
}
});
有上下文的问题是,除非在类上定义contextType,否则它是不可访问的。
至于什么是上下文,它是一个对象,就像props一样,从父对象传递给子对象,但它是隐式传递的,不需要每次都重新声明props。看见https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html
也许不是最好的解决方案,但它可以完成任务:
import { Link } from 'react-router-dom';
// Create functional component Post
export default Post = () => (
<div className="component post">
<button className="button delete-post" onClick={() => {
// ... delete post
// then redirect, without page reload, by triggering a hidden Link
document.querySelector('.trigger.go-home').click();
}}>Delete Post</button>
<Link to="/" className="trigger go-home hidden"></Link>
</div>
);
基本上,与一个操作相关的逻辑(在本例中为删除后操作)最终将调用重定向触发器。这并不理想,因为您将在标记中添加DOM节点“触发器”,以便在需要时方便地调用它。此外,您将直接与DOM交互,这在React组件中可能是不需要的。
不过,这种类型的重定向并不经常需要。因此,在组件标记中添加一两个额外的隐藏链接并不会造成太大的伤害,特别是如果您为它们提供了有意义的名称。