react-hooks - React - API Call to set mutliple state variables (Better Alternatives)
问题描述
I am learning react and during this process I was trying to set multiple state variables inside a single useEffect
hook. I just wanted to know, if my approach is the right way to set multiple state variables. Please take a look and advice if there is a better approach.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const App = () => {
const reqUrl = 'https://hn.algolia.com/api/v1/search?query=redux'
const initialStateValue = [{ id: 0, value: ' --- Select A State --- ' }];
const [initialJsonData, setInitialJsonData] = useState({ hits: [] });
const [tagTypes, setTagTypes] = useState([]);
const [stateSelected, setStateSelected] = useState(initialStateValue[0].value);
useEffect(() => {
axios(reqUrl).then(result => {
const tagTypeLocal = { ...result.data.hits[0] }
setTagTypes(tagTypeLocal._tags) --> setting the state variable tagTypes
console.log(tagTypeLocal._tags)
setInitialJsonData(result.data) --> setting the state variable initialJsonData
})
}, [])
解决方案
Yes, this is an acceptable implementation for updating multiple state items with the useEffect
hook.
And to address one of the comments to your question, it is more than fine to use multiple state variables as they might be updated at different times as suggested from the CodeSandbox you linked. In fact this approach is recommended in the React docs.
推荐阅读
- django - 无法使用扩展用户模型来满足 Django 表单
- unity3d - 在 Unity 中将材质应用于从 Blender 导出的模型
- java - 如何使用 CP Optimizer 为提货和送货操作建模容量限制?
- facebook - 为什么以及如何在 aws cognito 上检索使用 facebook 登录的用户信息?
- python - Python Asyncio如何从队列中连续运行任务/协程
- apache-camel - Apache Camel - 类型转换期间的错误或误解行为
- javafx - javafx中如何将一个变化的长数字绑定到一个标签上,使标签不断更新
- python - 在用户输入的某些点处切片和添加换行符的正确方法
- c++ - std::unordered_set::load_factor,为什么浮点数而不是双精度数?
- list - 如何为我的 3D 列表中的每个元素 = 1 分配一个随机数?