【发布时间】:2020-12-14 10:21:33
【问题描述】:
我需要更新序列中的相同状态:
// lets say this is the state
const [someState, setSomeState] = useState({a: 1, b: 1})
// and i need to update it like so
// from an external function
setSomeState({a: 2})
// wait until the first one is actually updates
// and do the next one
setSomeState({b: 2})
// wait until the second one is actually updates
// "tell" the parent function that both are updated
现在我这样做:
// i use a customized hook useStateCallback
function useStateCallback(initialState) {
const [state, setState] = useReducer((state, newState) => ({ ...state, ...newState }), initialState)
const cbRef = useRef(null)
const setStateCallback = (state, cb) => {
cbRef.current = cb
setState(state)
}
useEffect(() => {
if (cbRef.current) {
cbRef.current(state)
cbRef.current = null
}
}, [state])
return [state, setStateCallback]
}
// and execute it like so
// from outside of a component
export const someFunction = async setState => {
await setState({ a: 2 }, () => Promise.resolve())
await setState({ b: 2 }, () => Promise.resolve())
}
但是这个回调不能正常工作,调用函数实际上并没有等待状态变化。
所以我的问题是:
- useStateCallback 挂钩如何与
Promise.resolve()结合使用? -
Promise.resolve()在这种特殊情况下如何工作? - 如何一个接一个地更新相同的状态,只有在第一个更新(使用挂钩)时才会更新第二个状态,并“告诉”父函数他们都完成了更新?
【问题讨论】:
-
我们需要更多关于
setState()是什么的信息。它返回什么?它接受哪些论据?
标签: javascript reactjs async-await es6-promise