简体   繁体   English

为什么我在 React 中的钩子变量没有保持我设置的状态?

[英]Why is my hook variable in React not holding the state I set it to?

I am using React and Redux.我正在使用 React 和 Redux。 When my props.employees changes for the 1st time, useEffect runs and updates my teamsArr to the value of props.employees.当我的 props.employees 第一次更改时,useEffect 会运行并将我的 teamArr 更新为 props.employees 的值。

But my desire is to add the props.employees array to the teamsArr array that should already be filled with the previous props.employees array values.但我的愿望是将 props.employees 数组添加到应该已经用之前的 props.employees 数组值填充的 teamArr 数组中。

But instead, whenever I change the value of props.employees, my teamsArr variable is initially empty and then changes the value to solely the current props.employees value.但是,每当我更改 props.employees 的值时,我的 TeamsArr 变量最初为空,然后将该值更改为当前的 props.employees 值。

I've been struggling to figure out how to solve this, so any help would be very welcome.我一直在努力弄清楚如何解决这个问题,所以非常欢迎任何帮助。

const Employees = (props) => {
    const [teamsArr, setTeamsArr] = useState([])


    useEffect(() => {
        const updatedTeamsArr = [...teamsArr, props.employees]
        setTeamsArr(updatedTeamsArr)
        }
    ,[props.employees])

You can take advantage of passing a function to setTeamsArr您可以利用将函数传递给 setTeamsArr

useEffect(() => {
    setTeamsArr(prev => [...prev, ...props.employees])
    }
,[props.employees])

but in this case everytime prop.employees changes it'll be added but old values won't be removed.但在这种情况下,每次 prop.employees 更改时都会添加它,但不会删除旧值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM