React history.push 无法在 Home 组件中运行

React history.push not working from the Home component

我正在对我的 React 项目实施身份验证,并尝试在我的 Home 组件中使用登录表单。这是我的 Home 组件在附加了 Login 组件后的样子。

import Login from './Login'
import * as React from 'react';
import Box from "@material-ui/core/Box";

const Home = () => {
  return (
    <div>
      <Box sx={{
        width: 600,
        height: 150,
        backgroundColor: 'lightgrey',
        borderRadius: 16
      }}>
        {<h1>Welcome to our Podcast App</h1>}
        {<h2>Feel free to share your favorites or have fun listening to the ones available.</h2>}
      </Box><br/>
        < Login />
    </div>
  );
};

export default Home;

问题是,我想将我的用户重定向到播客页面,但 history.push 不工作。这是登录组件的外观。

import React from "react";
import { connect } from "react-redux";
import { loginUser } from "../actions/index";
import Button from "@material-ui/core/Button";
import { Box } from "@material-ui/core";

class Login extends React.Component {
  state = {
    email: "",
    password: "",
    error: false
  };

  handleChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value
    });
  };

  handleSubmit = (event) => {
    event.preventDefault();
    const { email, password } = this.state;
    this.props
      .dispatchLoginUser({ email, password }) 
      .then(() => this.props.history.push('/podcasts')) 
      .catch(() => this.setState({ error: true }));   
  };
  

  render() {
    return (
      <Box sx={{ p: 2, border: '1px solid grey' }}>
        <form onSubmit={this.handleSubmit} >
          <h3>Log In</h3>
          <p>{this.state.error && "Invalid email or password"}</p>
          <fieldset>
            <label htmlFor='email'>
              Email:
            </label>
            <input
              type='text'
              name='email'
              id='email'
              onChange={this.handleChange}
              value={this.state.email}
            />
          </fieldset>
          <fieldset>
            <label htmlFor='password'>
              Password:
            </label>
            <input
              type='password'
              name='password'
              id='password'
              onChange={this.handleChange}
              value={this.state.password}
            />
          </fieldset><br/>
          <Button variant="contained" size="small" color="inherit" type='submit'>Log In</Button>
        </form>
      </Box>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    dispatchLoginUser: (credentials) => dispatch(loginUser(credentials))
  };
};

export default connect(null, mapDispatchToProps)(Login);

如果我尝试从登录页面登录,它会成功。但它在主页上不起作用。我也尝试像另一个 post 建议的那样向我的项目添加历史记录,但它仍然不起作用。这是代码:

//history.js
import { createBrowserHistory } from 'history';

export default createBrowserHistory();
//index.js
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

ReactDOM.render(
  <Provider store={ store }>
    <Router history={history} >
      <App />
    </Router>
  </Provider> 
//The routes in App.js
<Route exact path='/' component={Home}/>
<Route exact path='/signup' component={Signup} />
<Route exact path='/login' component={Login} />  

是否可以让 history.push 从 Home 组件运行?欢迎任何建议。谢谢大家

在 react-router-dom 版本 6 useHistory() 替换为 useNavigate()

import {useNavigate} from 'react-router-dom'; 

const navigate = useNavigate(); 
navigate('/home')

Is it possible to make history.push work from the Home component?

是的,绝对是。您只需要从 Home 组件中的 props 对象对其进行解构。为此,Home 组件实际上需要有一个 defined/declared props 对象。

const Home = (props) => {
  // access props.history
  return (
    ...
    <Login history={props.history} />
    ...
  );
};

const Home = ({ history }) => {
  // access history
  return (
    ...
    <Login history={history} />
    ...
  );
};

Home是一个函数组件,所以也可以使用useHistory钩子传递。

const Home = () => {
  const history = useHistory();

  return (
    ...
    <Login history={history} />
    ...
  );
};