我有以下动作创建者:
export function scrolltoNextItem(item) {
return (dispatch, getState) => {
dispatch(appendItem(Item));
dispatch(
scrollToNextIndex(
getState().items.length - 1
)
)
}
}
问题是scrollToNextItem
在appendItem完成并且滚动位置最终不正确之前运行。我可以通过添加一个setTimeout
使脚本的执行在运行之前等待下一个滴答声来证明是这种情况scrollToNextItem
:
export function scrolltoNextItem(item) {
return (dispatch, getState) => {
dispatch(appendItem(Item));
setTimeout(() => {
dispatch(
scrollToNextIndex(
getState().items.length - 1
)
)
}, 0);
}
}
如何等待appendItem
动作完成?在标准React Land中,我只使用setState
回调:
this.setState({something: 'some thing'}, () => {
console.log('something is set');
});
但dispatch
不提供任何回调功能。
您始终可以将appendItem包装到promise中并dispatch
作为参数传递给它
const appendItem = (item, dispatch) => new Promise((resolve, reject) => {
// do anything here
dispatch(<your-action>);
resolve();
}
然后你可以这样称呼它 scrolltoNextItem
export function scrolltoNextItem(item) {
return (dispatch, getState) => {
appendItem(Item, dispatch).then(() => {
dispatch(
scrollToNextIndex(
getState().items.length - 1
)
)
})
}
}