简体   繁体   中英

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

I am using React and Redux. When my props.employees changes for the 1st time, useEffect runs and updates my teamsArr to the value of 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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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