da4*_*a45 3 reactjs react-hooks
如果我们想从远程服务器获取数据,然后将其作为初始状态传递给减速器,我们该如何进行?我试图在 useEffect 中调用 dispatch 但它被拒绝了,因为在 useEffect(...) 中调用钩子的规则被禁止了?,
有什么帮助吗?
将数据作为初始状态传递给 reducer 的唯一方法是在渲染组件之前获取数据。您可以在父级中执行此操作:
const Parent = () => {
const [data, setData] = useState(null)
useEffect(() => {
apiCall().then(response => {
setData(response.data)
})
}, [])
if (!data) return null
return <MyComponent data={data} />
}
const MyComponent = ({ data }) => {
const [state, dispatch] = useReducer(reducer, data)
... // utilize state
}
Run Code Online (Sandbox Code Playgroud)
.
上述方法是不可取的,因为它破坏了关注点分离。通常最好设置一个空初始状态并调用dispatch将其更改为所需状态:
const MyComponent () => {
const [state, dispatch] = useReducer(reducer, null)
useEffect(() => {
apiCall().then(response => {
dispatch({
type: 'INITIALIZE',
data: response.data
})
})
}, [])
if (!state) return null
... // utilize state
}
Run Code Online (Sandbox Code Playgroud)
.
| 归档时间: |
|
| 查看次数: |
3067 次 |
| 最近记录: |