Javascript React Hooks with React Router v4 - 如何重定向到另一条路由?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54579730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Hooks with React Router v4 - how do I redirect to another route?
提问by WD1
I have a simple react hooks application - a list of Todos - with react router v4
我有一个简单的 react hooks 应用程序 - 一个 Todos 列表 - 带有 react router v4
On the List of Todos, when a Todo is clicked I need to:
在待办事项列表中,当点击待办事项时,我需要:
- Dispatch the current todo in context
- Redirect to another route (from /todos to /todos/:id)
- 在上下文中分派当前的待办事项
- 重定向到另一个路由(从 /todos 到 /todos/:id)
In the previous React Class based implementation I could use this.context.history.push to redirect to another route.
在之前基于 React 类的实现中,我可以使用 this.context.history.push 重定向到另一个路由。
How would I handle that using React Hooks in combination of React Router v4 (in code below see my comment in function editRow())?
我将如何使用 React Hooks 结合 React Router v4(在下面的代码中查看我在函数 editRow() 中的注释)来处理这个问题?
Code below:
代码如下:
=====index.js=====
======index.js=====
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter} from "react-router-dom"
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
=====main.js=====
======main.js=====
import React from 'react'
import { Switch, Route } from 'react-router-dom'
import TodosList from './todoslist'
import TodosEdit from './todosedit'
const Main = () => (
<main>
<Switch>
<Route exact path="/todos" component={TodosList}/>
<Route exact path="/todos/:id" component={TodosEdit} />
</Switch>
</main>
)
export default Main
=====app.js=====
======app.js=====
import React, {useContext, useReducer} from 'react';
import Main from './main'
import TodosContext from './context'
import todosReducer from './reducer'
const App = () => {
const initialState = useContext(TodosContext);
const [state, dispatch] = useReducer(todosReducer, initialState);
return (
<div>
<TodosContext.Provider value={{state, dispatch}}>
<Main/>
</TodosContext.Provider>
</div>
)
}
export default App;
=====TodosContext.js=====
======TodosContext.js=====
import React from 'react'
const TodosContext = React.createContext({
todos: [
{id:1, text:'Get Grocery', complete:false},
{id:2, text:'Excercise', complete:false},
{id:3, text:'Drink Water', complete:true},
],
currentTodo: {}
})
export default TodosContext
=====reducer.js=====
=====reducer.js=====
import React from 'react'
export default function reducer(state, action){
switch(action.type){
case "GET_TODOS":
return {
...state,
todos: action.payload
}
case "SET_CURRENT_TODO":
return {
...state,
currentTodo: action.payload
}
default:
return state
}
}
=====Todos.js=====
======Todos.js=====
import React, {useState, useContext, useEffect} from 'react';
import TodosContext from './context'
function Todos(){
const [todo, setTodo] = useState("")
const {state, dispatch} = useContext(TodosContext)
useEffect(()=>{
if(state.currentTodo.text){
setTodo(state.currentTodo.text)
} else {
setTodo("")
}
dispatch({
type: "GET_TODOS",
payload: state.todos
})
}, [state.currentTodo.id])
const editRow = event =>{
let destUrlEdit = `/todos/${event.id}`
let obj = {}
obj.id = event.id
obj.text = event.text
dispatch({type:"SET_CURRENT_TODO", payload: obj})
//after dispatch I would like to redirect to another route to do the actual edit
//destUrlEdit
}
return(
<div>
<h1>List of ToDos</h1>
<h4>{title}</h4>
<ul>
{state.todos.map(todo => (
<li key={todo.id}>{todo.text}
<button onClick={()=>{
editRow(todo)}}>
</button>
</li>
))}
</ul>
</div>
)
}
export default Todos;
采纳答案by Shubham Khatri
Your problem is related to Programmatically navigating using react-router-v4 instead of with hooks,
您的问题与使用 react-router-v4 而不是钩子以编程方式导航有关,
In react-router-v4, you would get history from props if the Todos component is rendered as a child or Route or from an ancestor that is render form Route and it passed the Router props to it. However it is not receiving Router props, you can use withRouterHOC from react-routerto get the router props and call props.history.push(destUrlEdit)
在 react-router-v4 中,如果 Todos 组件被渲染为子组件或 Route 或从渲染表单 Route 的祖先并将路由器道具传递给它,您将从道具中获取历史记录。但是它没有接收路由器道具,您可以使用withRouterHOC fromreact-router获取路由器道具并调用props.history.push(destUrlEdit)
import React, {useState, useContext, useEffect} from 'react';
import TodosContext from './context'
import { withRouter } from 'react-router-dom';
function Todos(props){
const [todo, setTodo] = useState("")
const {state, dispatch} = useContext(TodosContext)
useEffect(()=>{
if(state.currentTodo.text){
setTodo(state.currentTodo.text)
} else {
setTodo("")
}
dispatch({
type: "GET_TODOS",
payload: state.todos
})
}, [state.currentTodo.id])
const editRow = event =>{
let destUrlEdit = `/todos/${event.id}`
let obj = {}
obj.id = event.id
obj.text = event.text
dispatch({type:"SET_CURRENT_TODO", payload: obj})
//after dispatch I would like to redirect to another route to do the actual edit
//destUrlEdit
props.history.push(destUrlEdit);
}
return(
<div>
<h1>List of ToDos</h1>
<h4>{title}</h4>
<ul>
{state.todos.map(todo => (
<li key={todo.id}>{todo.text}
<button onClick={()=>{
editRow(todo)}}>
</button>
</li>
))}
</ul>
</div>
)
}
export default withRouter(Todos);
回答by Lynden Noye
It's actually a lot simpler than the other answers, React Router v5.1 provides a useHistoryhook.
它实际上比其他答案简单得多,React Router v5.1 提供了一个useHistory钩子。
import React from 'react'
import { useHistory } from 'react-router-dom'
const MyComponent = () => {
const history = useHistory()
const handleButtonClick = (event) => {
history.push(event.target.value)
}
return (
<button
type="button"
value="/my/path"
onClick={handleButtonClick}
>
Navigate Me!
</button>
)
}
回答by Sten Muchow
Using react-redux and connected-react-router...
使用 react-redux 和 connected-react-router ...
import {useDispatch } from 'react-redux';
import { push } from 'connected-react-router';
export default () => {
const dispatch = useDispatch();
return (
<Button onClick={() => dispatch(push('/login'))}>
Login
</Button>
);
};

