gpt4 book ai didi

javascript - 将回调/ promise 从组件传递给 Action 创建者

转载 作者:行者123 更新时间:2023-11-29 21:01:29 27 4
gpt4 key购买 nike

我有一个 react 组件,我想在 redux 中设置一些状态,当设置状态时,我想在组件中做一些其他的事情。

 // Inside Component
onButtnClick() {
const currentTime = moment.tz('US/Eastern').valueOf();
this.props.updateDataInReduxState(currentTime, () => {
// this should not be called until current time is set.
this.props.openInputModalToShowTime();
});
}

// Inside actions
function updateDataInReduxState(currentTime, callback) {
// how can I call callback after state updates successfully,
// to ensure correct time is shown in the modal?
return {
type: UPDATE_TIME,
payload: currentTime
}
)

function openInputModalToShowTime() {
return {
type: SHOW_MODAL,
payload: true
}
}

// Modal Component listens on redux state state.showmodal, if true it opens
// and displays time stored in redux state state.currentTime

最佳答案

您不应该在另一个 Action 创建者(在您的情况下是函数 updateDataInReduxState)内部调度 Action 。 Action creators 只是用来发送一个 action,而这个 action 又被一个 reducer 监听并相应地改变状态。

你可以这样处理你的情况。

//Inside component, dispatch updateData action without any callback
onButtnClick() {
const currentTime = moment.tz('US/Eastern').valueOf();
this.props.updateDataInReduxState(currentTime);
}

//Now listen to your prop updates and once current time prop is set in your state, dispatch your openInputModalToShowTime action
componentWillReceiveProps(nextProps) {
if(nextProps.hasOwnProperty('currentTime') && nextProps.currentTime != null){
this.props.openInputModalToShowTime();
}
}

关于javascript - 将回调/ promise 从组件传递给 Action 创建者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46244130/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com