Reactjs 如果我需要进行一些有状态的编排,那么React钩子的最佳实践是什么?
我有两个不同的组件需要执行相同类型的编排:Reactjs 如果我需要进行一些有状态的编排,那么React钩子的最佳实践是什么?,reactjs,react-hooks,Reactjs,React Hooks,我有两个不同的组件需要执行相同类型的编排: useEffect(() => { async function fetchData() { if (route.params['id']) { const resConversation = await axios(`...`) setConversationState({ ...conversationState, currentC
useEffect(() => {
async function fetchData() {
if (route.params['id']) {
const resConversation = await axios(`...`)
setConversationState({ ...conversationState, currentConversation: resConversation.data })
const resParticipants = await axios(`...`)
setParticipants(resParticipants.data)
const resStream = await axios(`somestuff`)
setAudioState({ ...audioState, ...resStream })
}
}
fetchData()
}, [])
setAudioState和setConversationState来自useContext
对我来说,做这件事并保持代码干燥的最好方法是什么
我考虑了一个定制的useGetConversation钩子,但我只能在我的组件函数体内调用它。有更好的方法吗?如果您的呼叫彼此不依赖,请使用Promise.all并行调用,分解响应结构,然后进行设置 通过使用一个reducer通过useReducer设置状态,我还可以避免多次set调用 如果您的通话相互依赖,请先拨打电话,然后再设置状态:
useEffect(() => {
if (route.params['id']) {
return
}
async function fetchData() {
const resConversation = await axios(`...`)
const resParticipants = await axios(`...`)
const resStream = await axios(`somestuff`)
setConversationState(conversationState => ({ ...conversationState, currentConversation: resConversation.data }))
setParticipants(resParticipants.data)
setAudioState(audioState => ({ ...audioState, ...resStream }))
}
fetchData()
}, [])
您还可以捆绑调用API并将状态设置为单个函数,但我觉得这有点难以理解:
const callAndSet = async (axiosRequest, setter) => {
const res = await axios(axiosRequest)
setter(res)
}
useEffect(() => {
if (!route.params['id']) {
return
}
async function fetchData() {
await callAndSet(`...`, resConversation => setConversationState(conversationState => ({ ...conversationState, currentConversation: resConversation.data })))
await callAndSet(`...`, resParticipants => setParticipants(resParticipants.data))
await callAndSet(`somestuff`, resStream => setAudioState(audioState => ({ ...audioState, ...resStream })))
}
fetchData()
}, [])
但事实上,我需要在两个不同的地方做这件事——处理这件事的最佳方式是什么?承诺。所有这些都需要一个用户。或者一个自定义调用和设置钩子,如果你经常这样做的话。我应该把那个自定义调用/设置钩子放在哪里?它甚至不是一个自定义钩子。只是一个简单的包装函数。
const callAndSet = async (axiosRequest, setter) => {
const res = await axios(axiosRequest)
setter(res)
}
useEffect(() => {
if (!route.params['id']) {
return
}
async function fetchData() {
await callAndSet(`...`, resConversation => setConversationState(conversationState => ({ ...conversationState, currentConversation: resConversation.data })))
await callAndSet(`...`, resParticipants => setParticipants(resParticipants.data))
await callAndSet(`somestuff`, resStream => setAudioState(audioState => ({ ...audioState, ...resStream })))
}
fetchData()
}, [])