ReduxToolkit useSelector钩子:React功能组件在通过useDispatch更新所选的redux



我在一个测验游戏工作,我想要的SingleChoice组件从一个QuizApi获取SingleChoice问题。当用户单击开始按钮时,为了播放singleQuestionMode,组件应该获取问题并将其显示在屏幕上(为了测试目的,我只显示了一个,,hello"文本相反)。然后开始按钮应该消失(在它被点击之后)。

为了实现这一点,我创建了一个名为gameStarted的redux状态,这是一个布尔值。我使用useSelector()在组件内部导入状态,并让组件订阅该状态的状态更改。在return语句中,我使用{}注入一个三元运算符,该运算符渲染按钮(如果游戏尚未开始,即gamestarsted -state = false),并渲染,,hello"文本,让按钮消失,如果用户点击按钮启动SingleQuestionsMode(又名gameStarted已设置为true)。

但是如果我点击开始按钮,我可以在浏览器的devConsole中看到,问题被正确地获取,通过redux-devtools,我可以看到gameStarted redux状态被正确地设置为true(从最初的false),但是组件仍然不渲染(不显示"hello"占位符和按钮没有消失)。

浏览器中dev-console的截图: 按钮被点击前:点击前按钮

按钮被点击后:点击按钮后

为什么?即使我最初将gamstarted redux-state设置为true,它也会显示,,hello"-占位符文本而不是按钮。所以这一切似乎都是正确的设置,但有些东西阻止了渲染后gameststartredux状态被改变。也许我也用过redux-persist ?

下面是所有相关代码:

SingleChoice.js代码:

import React, { useEffect, useState} from 'react';
import {useSelector, useDispatch} from 'react-redux';
import {selectGameStatus, setGameStarted} from "../loginSlice";
export default function SingleChoice() {
const dispatch = useDispatch();
const [questions, setQuestions] = useState([]);
const gameStarted = useSelector(selectGameStatus);

const fetchSingleQuestions = async () => {
const questionData = await fetch('url-here');
const questions = await questionData.json();
setQuestions(questions.results)
console.log(questions.results);
}
const startGame = () => {
fetchSingleQuestions();
dispatch(setGameStarted());
}

return (
<div>
<h1>SingleChoiceMode</h1>
{!gameStarted ? <button onClick={startGame}>Spiel starten</button> : <div><h1>Hello</h1></div>}
</div>
)
}

具有上述gameStarted状态的切片代码:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

const initialState = {
loggedIn: false,
accountInfo: {
id: "",
username: "",
mail: "", 
password: "",
singlescore: "", 
multiscore: "", 
mixedscore: ""
},
gameStarted: false
};
export const LoginSlice = createSlice({
name: 'login',
initialState,
reducers: {
setLoginTrue: (state) => {
state.loggedIn = true;
},
setLoginFalse: (state) => {
state.loggedIn = false;
},
setAccountInfo: (state, action) => {
state.accountInfo = {
id: action.payload.id,
username: action.payload.username,
mail: action.payload.mail,
password: action.payload.password,
singlescore: action.payload.singlescore,
multiscore: action.payload.multiscore,
mixedscore: action.payload.mixedscore
}
},
setGameStarted: (state) => {
state.gameStarted = true;
},
setGameStopped: (state) => {
state.gameStarted = false;
}
}
});
export const selectLoginState = (state) => state.login.loggedIn;
export const selectAccountInfo = (state) => state.login.accountInfo;
export const selectGameStatus = (state) => state.gameStarted;
export const { setLoginTrue, setLoginFalse, setAccountInfo, setGameStarted, setGameStopped } = LoginSlice.actions;
export default LoginSlice.reducer;

redux-store的代码(我也使用redux-persist来保持用户的loggedIn):

import { configureStore } from '@reduxjs/toolkit';
import loginReducer from '../features/loginSlice';
import storage from "redux-persist/lib/storage";
import {combineReducers} from "redux"; 
import { persistReducer } from 'redux-persist'
const reducers = combineReducers({
login: loginReducer
})
const persistConfig = {
key: 'root',
storage
};
const persistedReducer = persistReducer(persistConfig, reducers);

const store = configureStore({
reducer: persistedReducer,
devTools: process.env.NODE_ENV !== 'production'
});
export default store;

Index.js代码:

ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);

组件App.js的代码,所有的东西都是路由和呈现的

import React from 'react';
import Home from "./features/Home";
import SingleChoice from "./features/modes/SingleChoice"
import MultipleChoice from "./features/modes/MultipleChoice"
import Mixed from "./features/modes/Mixed"
import Login from "./features/Login"
import Profile from "./features/Profile"
import Rankings from "./features/Rankings"
import NotFound from "./features/NotFound"
import Register from "./features/Register"
import Protected from "./features/Protected"
import { NavBar } from "./features/Navbar";
import './App.css';
import { Routes, Route } from "react-router-dom";
function App() {
return (
<div className="App">
<NavBar />
<Routes>
<Route path="/" element={<Home />} />
<Route element={<Protected />}>
<Route path="/single" element={<SingleChoice />} />
<Route path="/multiple" element={<MultipleChoice />} />
<Route path="/mixed" element={<Mixed />} />
<Route path="/profile" element={<Profile />} />
<Route path="/rankings" element={<Rankings />} />
</Route>
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="*" element={<NotFound />} />
</Routes>
</div>
);
}
export default App;

请帮助我,以便singlecchoice组件在导入redux-state更改后最终呈现。

InSingleChoice.js,而不是

const gameStarted = useSelector(selectGameStatus);
...
const startGame = () => {
fetchSingleQuestions();
dispatch(setGameStarted());
}

类型:

const { gameStarted } = useSelector((state) => state.login);
...
const startGame = () => {
fetchSingleQuestions();
dispatch(setGameStarted(true));
}

在<<BK_HR>strong> loginSlice.js 替换

setGameStarted: (state) => {
state.gameStarted = true;
},

由:

setGameStarted: (state, action) => {
state.gameStarted = action.payload;
},

demo: Stackblitz

相关内容

  • 没有找到相关文章

最新更新