【发布时间】:2020-06-06 14:38:48
【问题描述】:
在我的应用程序中,我有一个以某些值开头的初始状态。 在一个过程中,我需要为一个空数组改变这个状态,(也就是我的 Api 的返回)。
我正在尝试这样做,但状态的值不会改变。
我能做什么?
我的代码
import React, {useEffect, useState} from "react";
import "./style.scss";
import Services from "../../services/Services";
export default function Acoplamento({history, match}) {
const [veiculos, setVeiculos] = useState([]);
const [loading, setLoading] = useState(false);
const [type, setType] = useState(1);
const getAllVeiculos = async () => {
setLoading(true);
await Services.VeiculoServices.getAll().then(result => {
setVeiculos(result.data); // Here, i have a array with some objects
}).catch(error => {
error(error.message);
}).finally(() => setLoading(false));
return true;
}
const getOneVeiculos = async () => {
setLoading(true);
await Services.VeiculoServices.get().then(result => {
setVeiculos(result.data); // Here, my return is a empty array, but my state don't chage
}).catch(error => {
error(error.message);
}).finally(() => setLoading(false));
return true;
}
useEffect(() => {
if (type === 1) {
getAllVeiculos();
}
if (type === 2) {
getOneVeiculos();
}
}, [type]);
return (
<div>
<button onClick={() => setType(2)}>Click</button>
{veiculos.map(item => (
<div>{item.name}</div>
))}
</div>
);
}
【问题讨论】:
-
你提供的那段代码不是你的代码意外行为的来源,没有任何其他上下文是不可能帮助你的
-
你在哪里记录状态
-
@HagaiHarari,我编辑了问题并输入了所有代码。
-
@ShubhamKhatri 我输入了代码。
-
您在哪里以及如何准确记录您的状态并说它没有更新?
标签: reactjs react-hooks react-state-management react-state