如何使 useSelector() 工作(基本设置)?

How to make useSelector() work (basic setup)?

我被困在最基本的 React Redux 设置中。我的 useSelector 根本没有 return 任何值。这是代码: store.js:

import {createStore} from 'redux'

const initialState = {
    counter: 0
}

const counterReducer = ( state = {initialState}, action) => {
    switch (action.type) {
        case 'INCREMENT': return {counter: state.counter+1}
        case 'DECREMENT': return {counter: state.counter-1}
        default: return state
    }
}

const reduxStore = createStore(counterReducer, {initialState})

export default reduxStore

root index.js:

import {Provider} from 'react-redux'
import reduxStore from './components/store/store'

ReactDOM.render(
  <React.StrictMode>
    {/* Redux store provider */}
    <Provider store={reduxStore}>
    <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')

App.js:

import {useSelector} from 'react-redux'

function App() {
  const counter = useSelector ((state) => state.counter)

return (<p>Countamount: {counter}<p>)

您的减速器和商店的定义不正确。

您的状态如下所示:

{
  initialState: { counter: 0 }
}

我想你希望它看起来像这样:

{ counter: 0 }

您需要删除 reducer 中 state 参数的默认值,并将对 createStore 的调用更改为仅采用 initialState 而不是 {initialState}。例如

const counterReducer = (state, action) => {
    switch (action.type) {
        case 'INCREMENT': return {counter: state.counter+1}
        case 'DECREMENT': return {counter: state.counter-1}
        default: return state
    }
}

const reduxStore = createStore(counterReducer, initialState)