我正在尝试使用 react hooks 保存 api 响应并将其传递给功能 drawChart。在这段代码中,对象的更新状态没有传递给我的函数。将对象的更新状态传递给函数 drawChart 的正确方法是什么?
def get(self, request):
try:
payer_data = validate_payer(db=db,request =request,payer = payer,userid = userid)
BODY OF API
except Exception as e:
if isinstance(e,exceptions.NotAcceptable):
raise
elif isinstance(e,exceptions.PermissionDenied):
raise
else:
manager.create_from_exception(e)
return Response(AppResponse.msg(request, 400, 'Something went wrong.', 0, 0, 0), status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:2)
当你改变你的状态时,组件必须重新渲染以获得新的状态
你可以像这样写另一个useEffect
useEffect(() => {
axios.get(url)
.then(response => {
var obj = JSON.parse(response.data)
setResponseMonthly(obj);
})
.catch(err => console.log(err))
},[]);
useEffect(() => {
if(responseMonthly) drawChart(responseMonthly, 'month')
},[responseMonthly]);
或者你可以像这样调用你的函数
useEffect(() => {
axios.get(url)
.then(response => {
var obj = JSON.parse(response.data)
setResponseMonthly(obj);
drawChart(obj, 'month')
})
.catch(err => console.log(err))
},[]);
答案 1 :(得分:1)
您需要在 []
中传递要更改的任何变量 useEffect(() => {
if (responseMonthly) {
drawChart(responseMonthly, 'month')
return
}
axios.get(url)
.then(response => {
var obj = JSON.parse(response.data)
setResponseMonthly(obj);
})
.catch(err => console.log(err))
},[responseMonthly]);