简体   繁体   English

React useState:将子数组推入数组

[英]React useState: pushing a sub-array into an array

Am using function based component and am having trouble in pushing a subarray into a useState array.我正在使用基于 function 的组件,并且在将子阵列推入 useState 阵列时遇到了麻烦。 my code is shown below.我的代码如下所示。 There is an array called mode coming from the props which i need to append it as a sub array of more有一个名为mode的数组来自道具,我需要 append 它作为更多的子数组

const ViewCharts = (props) =>{

//other codes

let [more,setMore] = useState([])

useEffect(()=>{
        console.log(props.mode,' mode array')
        let temp = [...more,props.mode]
        console.log(temp, ': this will append to more')
        setMore(temp)
        setTimeout(()=>{
            console.log(more,'after setting')
        },2000)
},[//some value])

}

when the props.mode has value ['top','bottom'] i expect more to have value of [['top','bottom']] and when next time if the props.mode is ['top'] i need more to have [['top','bottom'],['top']] .props.mode的值为['top','bottom']我希望更多的值具有[['top','bottom']]以及下一次如果props.mode是 ['top'] 我需要更多[['top','bottom'],['top']] but this is what am getting when i run the above code.但这就是我运行上述代码时得到的结果。

["top"] mode array ["top"] 模式数组

["top"]: this will append to more" ["top"]: 这将 append 到更多"

[]: " after setting " []:“设置后

why the setMore is not adding array even when the temp is having the expected value.为什么即使温度具有预期值,setMore 也不添加数组。

If I remember correctly the useState variable will change value in the next render when you set it.如果我没记错的话, useState变量会在你设置它时在下一次渲染中改变值。 You are trying to read the new more value in the same render you've changed it (as you are reading it in the same effect you've set the value in) , which will be [] the first time as that's how you initialised it.您正在尝试在您更改它的同一渲染中读取新的more(因为您正在以与您设置值相同的效果读取它) ,这将是[]第一次因为这就是您初始化的方式它。

Try creating a second useEffect with a more dependency to see if it gives you the value you want:尝试创建具有more依赖关系的第二个useEffect以查看它是否为您提供所需的值:

// You can also just console.log() before the return, needing no `useEffect` to see if the value indeed changed.
React.useEffect(() => {
  console.log('More: ', more);
}, [more]);

https://reactjs.org/docs/hooks-state.html#recap https://reactjs.org/docs/hooks-state.html#recap

Line 9: When the user clicks, we call setCount with a new value.第 9 行:当用户点击时,我们使用新值调用 setCount。 React will then re-render the Example component, passing the new count value to it.然后 React 将重新渲染 Example 组件,将新的计数值传递给它。

I would suggest reading the hooks API to better understand how they work.我建议阅读钩子 API 以更好地了解它们的工作原理。

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

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