reactjs 我的react应用在Redux的商店更新中无法重新呈现

whhtz7ly  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(100)

我正在学习Redux,在此应用程序中,我使用react-redux和redux,我没有改变商店的状态,但我的应用程序仍然没有重新渲染
我有一个基本的计数器应用程序,你按+键数字增加,你按-键它减少
我的代码:
近似值:'

import './App.css';
import { useDispatch } from 'react-redux';
import { store } from './store';

function App() {
  const dispatch = useDispatch();
  const handleIncrease = () => {
    console.log("+");
    dispatch({
      type : 'aumentar'
    })
    console.log(store.getState());
  }
  const handleDecrease = () => {
    console.log("-");
    dispatch({
      type : 'restar'
    })
  }
  return (
    <div className="App">
      <h1>Contador</h1>
      <h3>{store.getState()}</h3>
      <button onClick={handleIncrease}>+</button>
      <button onClick={handleDecrease}>-</button>
    </div>
  );
}

export default App;

'
索引. js:'

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);

'
存储. js '

import { legacy_createStore as createStore } from "redux";

let initialState = 0;

const reducer = (state = initialState, action) => {
    switch(action.type){
        case 'aumentar' :
            return state + 1;
        case 'restar' :
            return state - 1;
        default :
            return state;
    }
}

export const store = createStore(reducer);


'

6ie5vjzr

6ie5vjzr1#

您需要使用useSelector来访问状态中的条目:

// 1. import the hook
import { useDispatch, useSelector } from 'react-redux';
import { store } from './store';

function App() {
  const dispatch = useDispatch();
  // 2. use it to extract what you need
  const count = useSelector(state => state);
  const handleIncrease = () => {
    console.log("+");
    dispatch({
      type : 'aumentar'
    })
  }
  const handleDecrease = () => {
    console.log("-");
    dispatch({
      type : 'restar'
    })
  }

  // 3. use the extracted variable inside JSX
  return (
    <div className="App">
      <h1>Contador</h1>
      <h3>{count}</h3>
      <button onClick={handleIncrease}>+</button>
      <button onClick={handleDecrease}>-</button>
    </div>
  );
}

当你的状态变得更加复杂/你将使用更多的归约器时,你的代码将看起来像:

const whatYouNeed = useSelector(state => state.reducerName.something);

相关问题