我一直在尝试使用我的redux知识来构建小项目,以便在这个主题上更多地训练自己。最近,我一直在尝试使用redux,但我没有得到任何错误,也没有开发工具的错误,我的页面是空白的。我将张贴我的代码下面,所以它更清楚。所以我开始我的代码与基本的redux样板,我记住了。我创建了一个userslice和一个store,然后将store作为的 Package 器提供,但在花了几个小时后,我无法修复代码,代码应该给予我初始化的useselector挂钩在div中返回用户名,但它似乎不起作用
App.js:
import React from 'react';
import { useSelector } from 'react-redux';
import './App.css';
function App() {
const username = useSelector(state => state.username)
return (
<div className="App">
{username}
</div>
);
}
export default App;
userSlice.js
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name:'user'
,
initialState:{
username:'Tony stark',
post:'',
},
reducers:{
updatePost:(state,action)=>{
state.username = action.payload;
}
}})
export const { updatePost} = userSlice.actions;
export default userSlice.reducers;
store.js
import { configureStore } from '@reduxjs/toolkit';
import userSlice from '../redux/userSlice'
export const store = configureStore({
reducer: {
user: userSlice,
},
});
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from '../src/redux/store'
import App from './App';
import './index.css';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
1条答案
按热度按时间yhxst69z1#
如果它在userSlice中,则需要从根状态的
user
属性获取它,如下所示:const username = useSelector(state => state.user.username)
初始Redux状态应如下所示: