【问题标题】:my redux is not working the way i wrote it down我的 redux 没有按照我写下来的方式工作
【发布时间】: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


    【解决方案1】:

    如果它在 userSlice 中,你需要从根状态的 user 属性中获取它,如下所示:

    const username = useSelector(state =&gt; state.user.username)

    您的初始 Redux 状态应如下所示:

    { // <-- state
      user: { // <-- state.user
        username: 'Tony stark', // <-- state.user.username
        post: '' // <-- state.user.post
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-13
      • 2012-01-13
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多