Reactjs 使用useEffect存储响应以避免使用react钩子重新渲染
我正在使用React钩子并试图弄清楚,如何将api调用的响应Reactjs 使用useEffect存储响应以避免使用react钩子重新渲染,reactjs,react-hooks,Reactjs,React Hooks,我正在使用React钩子并试图弄清楚,如何将api调用的响应response.data.\u embedded.assets存储在状态变量中 使用setAssets(response.data.\u embedded.assets)因重新渲染而不工作。所以我决定使用useffect,如下代码所示,但这违反了react的规则 钩子-钩子只能在函数组件的主体内部调用。我知道,useffect应该根据react hooks在外部定义,但是我如何将响应存储在状态变量中?请告知 const [select
response.data.\u embedded.assets
存储在状态变量中
使用setAssets(response.data.\u embedded.assets)代码>因重新渲染而不工作。所以我决定使用useffect
,如下代码所示,但这违反了react的规则
钩子-钩子只能在函数组件的主体内部调用。我知道,useffect
应该根据react hooks在外部定义,但是我如何将响应存储在状态变量中?请告知
const [selectedTabIndex, setselectedTabIndex] = useState(0);
const [assets,setAssets] = useState([]);
let companyCategory;
axios
.get(url, {
params: {
assetCategoryId: selectedTabIndex
}
}).then(response => {
if (sessionStorage.getItem('companyCategory') !== null) {
companyCategory = JSON.parse(sessionStorage.getItem('companyCategory') )
}
console.log("Inside response of web api call");
console.log(response.data._embedded.assets);
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setAssets(response.data._embedded.assets);
}, []);
//setAssets(response.data._embedded.assets);
}).catch(err => console.log(err));
在类组件中,上面的状态变量声明在响应中如下所示:
this.setState({
companyCategory: companyCategory,
assets: response.data._embedded.assets
})
如果组件在更改时不需要渲染,请不要将其置于状态。您可以在组件中有一个模块范围变量并使用它
使用类组件,您还可以将它放在这个上,我会将整个get请求有效地使用
const [selectedTabIndex, setselectedTabIndex] = useState(0);
const [assets,setAssets] = useState([]);
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
let companyCategory;
axios
.get(url, {
params: {
assetCategoryId: selectedTabIndex
}
}).then(response => {
if (sessionStorage.getItem('companyCategory') !== null) {
companyCategory = JSON.parse(sessionStorage.getItem('companyCategory') )
}
console.log("Inside response of web api call");
console.log(response.data._embedded.assets);
setAssets(response.data._embedded.assets);
}).catch(err => console.log(err));
}, []);
如果你不想使用数据,为什么要获取数据,
我们也不能在函数中使用react钩子
- 来自React函数组件的调用挂钩
- 从自定义钩子调用钩子
您使用setAssets(response.data.\u embedded.assets)说;由于重新渲染而无法工作
,但这没有意义。在收到响应后,您是否应该重新渲染,因为此时您才有实际数据要显示?啊,我现在明白了。我认为您要做的是将Axios调用放在useffect(()=>{},[])
中(在[]
中没有列出任何依赖项的useffect
相当于componentDidMount
),然后从中调用setAssets
。获得过多重新渲染的原因是每次重新渲染都会重新执行API调用,然后更新状态,重新渲染组件,触发API调用,等等,当我使用setAssets(response.data.\u embedded.assets)时代码>我可以在控制台日志中看到某种循环,这种循环从未停止过。这可能是什么原因造成的?请检查我之前的评论:)好的,你的意思与凯文·C·弗隆(Kevin C.Ferron)在下面的回答中提到的类似?