Redux更新状态后如何触发回调?

jutyujz0  于 6个月前  发布在  其他
关注(0)|答案(7)|浏览(81)

在React中,状态不是即时更新的,所以我们可以在setState(state, callback)中使用callback。但是在Redux中怎么做呢?
在调用this.props.dispatch(updateState(key, value))之后,我需要立即对更新后的状态执行一些操作。
有没有什么方法可以像在React中一样调用一个带有最新状态的回调?

vsnjm48y

vsnjm48y1#

组件需要更新以接收新 prop 。

有很多方法可以实现你的目标:

1. componentDidUpdate检查value是否更改,然后执行操作。

componentDidUpdate(prevProps){
     if(prevProps.value !== this.props.value){ alert(prevProps.value) }
  }

字符串

2. redux-promise(中间件将分发promise的解析值)

export const updateState = (key, value)=>
Promise.resolve({
  type:'UPDATE_STATE',
  key, value
})


然后在组件中

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})

2. redux-thunk

export const updateState = (key, value) => dispatch => {
  dispatch({
    type: 'UPDATE_STATE',
    key,
    value,
  });
  return Promise.resolve();
};


然后在组件中

this.props.dispatch(updateState(key, value)).then(()=>{
   alert(this.props.value)
})

qeeaahzv

qeeaahzv2#

使用Hooks API:
useEffect以prop作为输入。

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

export default function ValueComponent() {
   const value = useSelector(store => store.pathTo.value)

   useEffect(() => {
     console.log('New value', value) 
     return () => {
        console.log('Prev value', value) 
     }

   }, [value])

   return <div> {value} </div>
}

字符串

v2g6jxz6

v2g6jxz63#

关于React最重要的一点是单向数据流。在你的例子中,这意味着调度动作和状态更改处理应该是解耦的。
你不应该想“我做了A,现在X变成了Y,我来处理它”,而是“当X变成Y时我该怎么办“,这与A没有任何关系。除了你的组件,存储状态可以从多个源更新,时间旅行也可以改变状态,它不会通过你的A调度点。
基本上,这意味着您应该使用@Utro提出的componentWillReceiveProps

vvppvyoh

vvppvyoh4#

你可以使用subscribe监听器,当一个动作被调度时,它会被调用。在监听器中,你会得到最新的存储数据。
http://redux.js.org/docs/api/Store.html#subscribelistener

a7qyws3x

a7qyws3x5#

你可以在回调函数中使用形转换函数

myThunk = cb => dispatch =>
  myAsyncOp(...)
    .then(res => dispatch(res))
    .then(() => cb()) // Do whatever you want here.
    .catch(err => handleError(err))

字符串

v1l68za4

v1l68za46#

作为一个简单的解决方案,您可以使用:用途:redux-promise
但是如果你使用redux-thunk,你应该这样做:

function addCost(data) {
  return dispatch => {
    var promise1 = new Promise(function(resolve, reject) {
      dispatch(something);
     });
    return promise1;
  }
}

字符串

zpjtge22

zpjtge227#

reduxdispatch返回一个promise,你可以像这样从它链接出去。

const submissionPromise: any = dispatch(submitFundRequest())
        submissionPromise
            .then((response: any) => {
                if(response.error) {
                    return console.log('There was an error', response)
                }
                Swal.fire({
                    title: 'Submission',
                    text: 'You have successfully submitted the requisition'
                })
            })
            .catch((err: any) => {
                console.log('Submission failed', err)
            })

字符串
response.error仅在thunk被拒绝时设置。在submitFundRequest thunk中,您可以执行以下操作来拒绝。

export const submitFundRequest = createAsyncThunk(
    'fundRequest/submitFundRequest',
    async function submit(payload, thunkAPI) {
        try {
            ...
        } catch(e: any) {
            const error = { message: e.response.statusMessage }
            return thunkAPI.rejectWithValue(error)
        }
    }
)

相关问题