rempei
@rempei

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Redux ページ切り替わらない

解決したいこと

タイトルの通りなのですが原因がわかりません。
reduxを使う前はちゃんとページが切り替わっていたのですが…

該当するソースコード

import './App.css';

import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux'
import LoginForm from './component/Login/LoginForm';
import MainContainer from './component/MainContainer/MainContainer';


function App() {
  const loggedIn = useSelector((state) => state.auth.loggedIn)

  return (
    <Router>
      <div className="App">
        <Routes>
          <Route path="/login" element={<LoginForm />}></Route>
          { loggedIn ?
            <Route path="/main" element={<MainContainer />}></Route>
            : 
            ""
          }
          <Route index element={<Navigate to="/login" />} ></Route>
        </Routes>
      </div>
    </Router>

  );
}

export default App;

MainContainer.js

import React from "react";

function MainContainer() {
  return (
    <div>
      main page
    </div>
  )
}

export default MainContainer

LoginForm.js

import "./LoginForm.css"

import { login } from "../../store/authSlice"

import React from "react"
import { useState } from "react"
import { useDispatch, useSelector } from "react-redux"


function LoginForm() {

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const loggedIn = useSelector((state) => state.auth.loggedIn)

  const dispatch = useDispatch()

  const handleSubmit = (e) => {
    e.preventDefault()
    dispatch(login())
    console.log("state: " + loggedIn)
  }

  return (
    <div style={{
      position: "relative",
    }}>
      <div className="login-form">
        <form onSubmit={handleSubmit}>
        <div className="username">
            <label htmlFor="username">ユーザー名:&nbsp;</label>
            <input
              type="text"
              id="username"
              name="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          </div>
          <div className="password">
            <label htmlFor="password">パスワード:&nbsp;</label>
            <input
              type="password"
              id="password"
              name="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>
          <button type="submit" className="submit-btn">ログイン</button>
        </form>
      </div>
    </div>
  )
}

export default LoginForm

authSlice.js

import { createSlice } from "@reduxjs/toolkit"

export const authSlice = createSlice({
  name: "auth",
  initialState: {
    loggedIn: false,
  },
  reducers: {
    login: (state) => {
      state.loggedIn = true
    },
    logout: (state) => {
      state.loggedIn = false
    },
  },
})

export const { login, logout } = authSlice.actions

export default authSlice.reducer

store.js

import { configureStore } from '@reduxjs/toolkit'
import authReducer from './authSlice'

export const store = configureStore({
  reducer: {
    auth: authReducer,
  },
})

今はログインボタンを押すと、
loginアクションがdispatchされて、
stateのloggedInがtrueになり、
MainContainerコンポーネントが表示されるようにしていますがloggedInがtrueになってもページが切り替わりません。
なぜかわかる方がいらっしゃいましたら教えてほしいです。

Windows10
    "@reduxjs/toolkit": "^1.9.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.1.2",
    "react-router-dom": "^6.16.0",
    "react-scripts": "5.0.1",
    "redux": "^4.2.1",
0

1Answer

今のコードではRoute(新しいURL)を追加しただけです。
LoginForm.jsのhandleSubmitでloggedInが変わってからURLを切り替える処理を入れないと行けないです。

import "./LoginForm.css"

import { login } from "../../store/authSlice"

import React from "react"
import { useState, useEffect } from "react"
import { useDispatch, useSelector } from "react-redux"
// ライブラリ追加
import { useNavigate } from "react-router-dom"

function LoginForm() {

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const loggedIn = useSelector((state) => state.auth.loggedIn)

  const dispatch = useDispatch()

  // Navigate追加
  const navigate = useNavigate()

  // loggedInがtrueになるとURLを切り替える
  useEffect(() => {
    loggedIn && navigate("/main")
  }, [ loggedIn ])

  const handleSubmit = (e) => {
    e.preventDefault()
    dispatch(login())
    console.log("state: " + loggedIn)
  }

  return (
    <div style={{
      position: "relative",
    }}>
      <div className="login-form">
        <form onSubmit={handleSubmit}>
        <div className="username">
            <label htmlFor="username">ユーザー名:&nbsp;</label>
            <input
              type="text"
              id="username"
              name="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          </div>
          <div className="password">
            <label htmlFor="password">パスワード:&nbsp;</label>
            <input
              type="password"
              id="password"
              name="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>
          <button type="submit" className="submit-btn">ログイン</button>
        </form>
      </div>
    </div>
  )
}

export default LoginForm
2Like

Comments

  1. @rempei

    Questioner

    ありがとうございました!

Your answer might help someone💌