【发布时间】:2022-12-09 23:01:35
【问题描述】:
我一直在尝试使用我的 redux 知识来构建小项目,以便在该主题上更多地训练自己。最近,我一直在尝试使用 redux,但我没有收到任何错误,也没有开发工具错误,而且我的页面是空白的。我会在下面发布我的代码,这样更清楚。 所以我用我记住的基本 redux 样板开始我的代码。我创建了一个 userslice 和一个商店,然后我提供了商店作为包装器,但在花了几个小时后我无法修复代码代码应该只使用我初始化的 useselector 钩子给我返回 div 中的用户名但是它似乎不起作用
应用程序.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;
商店.js
import { configureStore } from '@reduxjs/toolkit';
import userSlice from '../redux/userSlice'
export const store = configureStore({
reducer: {
user: userSlice,
},
});
索引.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))
【问题讨论】:
标签: javascript reactjs redux react-redux react-state-management