如何动态地将 map 函数用于钩子 useState 属性 [英] How to use map function for hooks useState properties dynamically
本文介绍了如何动态地将 map 函数用于钩子 useState 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题与这个问题几乎相同一>.
在这种情况下,这个人有一张以硬编码方式创建的状态图:
In this case, the person has a map of states created in a hard coded way:
const App = props => {
const [state, changeState] = useState({
name: "",
eventTitle: "",
details: "",
list: "",
toggleIndex: "",
editName: "",
editEventTitle: "",
editDetails: "",
});
不同之处在于我想动态创建这些状态,从另一个组件接收它们.我尝试过这样的事情,但显然没有用:
The difference is that I want to create those states dynamically, receiving them from another component. I tried something like this but it obviously did not work:
const App = props => {
const [state, changeState] = useState({
props.inputs.map((input, i) =>
input = ""
)
});
你知道有什么解决办法吗?
Do you know any solution for this?
推荐答案
假设 props.input
只是一个你想要的键的数组,你可以通过遍历数组和使用 []
Assuming props.input
is just an array of the keys you want, you can populate the state object by iterating through the array and dynamically assigning the state object key with []
const [state, changeState] = useState({});
useEffect(() => {
props.input.forEach(item => changeState(prevState => ({...prevState, [item]: "" })));
}, [props.input])
这篇关于如何动态地将 map 函数用于钩子 useState 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文