Programing

이번의history.properties/"는 나를 홈페이지로 리디렉션하지 않는다.

c10106 2022. 3. 25. 21:05
반응형

이번의history.properties/"는 나를 홈페이지로 리디렉션하지 않는다.

이 로그인 페이지를 홈 페이지로 리디렉션하려고 하는데 어떤 이유로 인해this.props.history.push('/')방향을 바꾸는 게 아니야나는 a를 가지고 있다.handleSubmit내가 로그인 버튼을 누른 후에 실행되도록 되어 있다.나는 무슨 일이 일어나고 있는지 잘 모르겠다.로그인 버튼을 누르면handleSubmit그러나, 그것은 정확히 다음에서 잡힌다.this.props.history.push('/')어떤 도움이라도 감사하다.

앱.js

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <Provider store={store}>
          <Router>
            {/* <Navbar /> */}
              <div className="container">
                <Routes>
                  <Route exact path="/" element={<Home/>} />
                  <Route exact path="/loginUser" element={<Login/>} />
                  <Route exact path="/createUser" element={<Signup/>} />
                </Routes>
              </div>
          </Router>
        </Provider>
      </MuiThemeProvider>
    );
  }
}

export default App;

로그인.js

class Login extends Component {
    constructor(){
        super();
        this.state = {
            email: '',
            password: '',
            errors: {}
        }
    }

    handleSubmit = (event) => {
        event.preventDefault();
        const userData = {
            email: this.state.email,
            password: this.state.password
        }
        
        axios
        .post("/loginUser", userData)
        .then(res => {
            console.log(res.data);
            localStorage.setItem('FBIdToken', `Bearer ${res.data.token}`);
            this.props.history.push('/')
        })
        .catch((err) => {
            console.log("ERROR inside loginUser.js");
        })
    }
    // Combine handleEmailChange and handlePasswordChange
    handleEmailChange = (event) => {
        this.setState({
            email: event.target.value
        })
    }
    handlePasswordChange = (event) => {
        this.setState({
            password: event.target.value
        })
    }

    render() {
        const { classes } = this.props;
        return (
            <Grid container className={classes.form}>
                <Grid item sm/>
                <Grid item sm>
                    <img src={HeroLogo} alt="CompanyLogo" className={classes.logo}/>
                    <Typography variant="h2" className={classes.pageTitle}>
                        Login
                    </Typography>
                    {/* Do we need to validate the email?? */}
                    <form noValidate onSubmit={this.handleSubmit}>
                        <FormControl margin="normal" variant="outlined" sx={{width:'50ch'}}>
                            <InputLabel htmlFor="email">Email</InputLabel>
                            <OutlinedInput
                                id="email"
                                type="email"
                                value={this.state.email}
                                className={classes.textField}
                                onChange={this.handleEmailChange}
                                label="Email"
                            />
                        </FormControl>
                        <br/>
                        <FormControl margin="normal" variant="outlined" sx={{width:'25ch'}}>
                            <InputLabel htmlFor="password">Password</InputLabel>
                            <OutlinedInput
                                id="password"
                                type="password"
                                value={this.state.password}
                                className={classes.textField}
                                onChange={this.handlePasswordChange}
                                label="Password"
                            />
                        </FormControl>
                        <br/>
                        <Button 
                            type="submit"
                            variant="contained"
                            color="primary"
                            className={classes.button}
                        >
                            LOGIN
                        </Button>
                        <br/>
                        <small>Don't have an account? <Link to="/createUser">Sign up</Link></small>
                    </form>
                </Grid>
                <Grid item sm/>
            </Grid>
        )
    }
}

꾸러미json

{
  "name": "derms-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.12.3",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.24.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-redux": "^7.2.6",
    "react-router-dom": "^6.1.1",
    "react-scripts": "4.0.3",
    "redux": "^4.1.2",
    "redux-thunk": "^2.4.1",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "https://north*******************************cloudfunctions.net/api"
}

몇 가지 이유로 어떤 오류도 발견하지 못했다니 놀랍다.

  1. react-router-domv6에서 더 이상 a를 표시하지 않음history항법에 사용할 물체A로 대체되었다.useNavigatea를 돌려주는 고리를 걸다navigate기능을 하다
  2. react-router-domv6Route구성 요소도 더 이상 어떤 경로 소품(예: , , , , )을 통과하지 않으며, 단지 존재하지 않는다.바꾸어 말하면, 환언하면this.props.history정의되지 않았으므로 를 호출할 때 오류를 발생시켜야 함push기능을 하다

이후Login사용자 정의 생성에 필요한 클래스 구성 요소withRouter구성 요소:navigate기능을 발휘하여 에 전달하다.Login소품으로

const withRouter = Component => props => {
  const navigate = useNavigate();
  return (
    <Component {...props} navigate={navigate} />
  );
};

...

class Login extends Component {
  constructor(){
    super();
    this.state = {
        email: '',
        password: '',
        errors: {}
    }
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const userData = {
      email: this.state.email,
      password: this.state.password
    }
    
    axios
    .post("/loginUser", userData)
    .then(res => {
      console.log(res.data);
      localStorage.setItem('FBIdToken', `Bearer ${res.data.token}`);
      this.props.navigate('/');
    })
    .catch((err) => {
      console.log("ERROR inside loginUser.js");
    })
  }

  ...

  render() {
    ...
    return (
      ...
    )
  }
}

export default withRouter(Login);

참조URL: https://stackoverflow.com/questions/70374596/this-props-history-push-isnt-redirecting-me-to-homepage

반응형