【问题标题】:Get updated redux state after dispatch派发后获取更新的 redux 状态
【发布时间】:2021-12-10 17:14:51
【问题描述】:

这是我的 reducer.js

const initialState = {
    counter: 0
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'increase':
            state = { ...state, counter: state.counter + 1 }
            break
        default:
            break
    }
    return state
}

export default reducer

这是我的 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'
import reducer from './reducer'

const store = createStore(reducer, applyMiddleware(thunk))

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

这是我在 React App.js 中的代码

import React from 'react'
import { useDispatch, useSelector } from 'react-redux'

function App() {

    const dispatch = useDispatch()
    const counter = useSelector(state => state.counter)

    const increment = (dispatch) => {
        return function () {
            return Promise.resolve(dispatch({ type: 'increase' }))
        }
    }

    const myFunc = increment(dispatch)

    const onClickIncrease = async () => {
        console.log('Before dispatch:', counter)
        myFunc().then(() => {
            console.log('After dispatch:', counter) *** // Why this line prints the same value as Before dispatch ***
        })
    }

    return (
        <div>
            <button onClick={onClickIncrease}>
                +
            </button>
        </div>
    )
}

export default App

当我点击+ 按钮三下时,我看到:
发货前:0
发货后:0
发货前:1
发货后:1
发货前:2
发货后:2

我不明白为什么之前和之后打印的计数器是一样的。如果我想看到这样的东西,谁能建议我该怎么做:
发货前:0
发货后:1
发货前:1
发货后:2
发货前:2
发货后:3

【问题讨论】:

  • 商店内的计数器值是否更新?你也可以发布reducer代码吗?
  • @Amruta 当然,我刚刚编辑了我的帖子。
  • 您已经在onClickIncrease 回调范围内关闭了counter 值,所以它不会在那里改变。这似乎是一些 微不足道的例子,但您要解决什么真正的 问题?实际用例是什么?如果您只想要“之前”和“之后”,那么将“之后”放在 useEffect 中,并依赖于 counter。它会在状态值更新时记录。
  • 认为您可以向我们提供您的代码的运行代码和框,我们可以实时检查和调试?从我所见,您似乎正在尝试将更新的状态从 thunk 返回到 Promise 链中的 UI。
  • @DrewReese 我只想在调度后立即处理更新的状态。正如您建议的那样,使用 useEffect 并依赖于 counter 对我有用。谢谢你们的cmets。

标签: reactjs redux react-redux state dispatch


【解决方案1】:

这是因为 Redux 调度的动作调用是异步的,所以你可以直接在你的动作中打印一些东西:

case 'increase':
  state = { ...state, counter: state.counter + 1 }
  console.log('after')
  break

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 2016-08-26
    • 2020-04-22
    • 1970-01-01
    • 2018-10-28
    • 2020-06-10
    • 2023-03-22
    • 2018-04-17
    相关资源
    最近更新 更多