反应 useState 不断给我未定义 [英] React useState keep giving me undefined

查看:49
本文介绍了反应 useState 不断给我未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const [urlList, setUrlList] = useState();

onClick={function(){
                                setUrlList(item.num);
                                console.log(item.num);
                          
                                callDayList();
                            }}

  1. 这段代码是关于什么的?

有一个表格,如果我点击一个 url,它会给出 item.num(1,2,3...).并通过 callDayList 函数,该数字转到后端(node.js).

there is a table, and if I click a url, it gives item.num(1,2,3...). and through the callDayList func, the number goes to backend(node.js).

  1. 有什么问题?

问题是状态urlList,没有正确的数字,只有未定义.console.log 的结果只是未定义.但是,在 chrome 上,我发现状态正在正确更改,但是更改速度有点慢,状态值显示了最后一次单击的状态(不确定您是否理解,第二次单击时,状态值是第一次单击的状态.).

the problem is the state urlList, does not have proper number, but only undefined. the outcome of console.log is only undefined. however, on chrome, I found that the state is changing correctly, however the speed of change bit slow and the value of state showing me the state of last click(not sure you understand, on second click, the value of state is the first click's state.).

3.我尝试了什么?

上网查了一下,觉得是渲染的问题.因为 useState 不会立即应用更改.我认为这就是一直显示我未​​定义的原因,因为在第一次点击时,状态中没有任何值(而在第二次点击时,它显示了第一次点击的状态值.)

I have searched internet, and I think this is the problem of rendering. because useState does not apply changes immediately. and I think this is the reason keep showing me undefined, because on first click, there is no value in state(and on second click, it shows the value of state of first click.)

解决方案之一是像 ...item.num (add"...") 这样的代码,但是没有用.第二个是把状态放在一个 var 中,比如 var _num = urlListconsole.log(_num) 但也没有工作.

one of the solution was code like ...item.num (add"...") but, did not work. second was put the state in a var, like var _num = urlList and console.log(_num) but also did not work.

实际上,我已经通过不使用状态解决了这个问题,而是将 item.num 放在一个 var 中并将其发送到后端,但我想了解为什么它不能通过 useState 工作.

actually, I have already solved this problem by not using state, but put the item.num in a var and send it to backend, but I want to understand why it is not working through useState.

推荐答案

setUrlList(item.num); 这是异步的.你需要使用 useEffect 钩子来做任何应该在 urlList 改变时发生的事情.试试下面:

setUrlList(item.num); this is asynchronous. You need to use a useEffect hook to do anything that should happen when urlList changes. Try below:

import {useEffect} from 'react';

const [urlList, setUrlList] = useState();

const callDayList = () => { 
     console.log(urlList); 
     Axios.post('localhost:3001/api/get',{ passNum : urlList, });
}

useEffect(() => {callDayList();}, [urlList]);

在您的元素中,

onClick={function(){ setUrlList(item.num);}}

这篇关于反应 useState 不断给我未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆