我当前正在尝试创建一个useRadioList()
挂钩,以跟踪给定组件中所有子项上的isExpanded
道具(当一个子项切换为isExpanded
时,另一个子项-toggle)
我这样做的方式一直是:
isExpanded
道具// useRadioList.jsx
import React, { Children, isValidElement, cloneElement, useState, useEffect } from "react"
export default (children, allowMultiple = true) => {
// 1) Setup initial list
const [radioList, setRadioList] = useState(Array(children.length).fill(false))
// 2) Map radioList values to component children on initial render, and do so again if radioList changes
useEffect(() => {
Children.map(children, (child, idx) => {
if (!isValidElement(child)) {return}
return cloneElement(child, {isExpanded: radioList[idx]})
})
}, [radioList])
// 3) Declare "toggle()" to modify the list that keeps track of what indexes are active
const toggle = (targetIndex) => {
let newList = radioList.map((item, idx) => {
if (allowMultiple) {
return targetIndex == idx ? !item : item
} else {
return targetIndex == idx ? !item : false
}
})
setRadioList(newList)
}
return toggle
}
// expected: const toggle = useRadioList(children)
当我调用切换按钮时,出现以下错误:
警告:通过useState()和useReducer()挂钩进行状态更新 不支持第二个回调参数。产生副作用 渲染后,使用useEffect()在组件主体中声明它。
编辑:
setRadioList(...newList) ----> setRadioList(newList)
不再出现callback
错误,现在看来我无法有效地将状态映射到子级,因为isExpanded
道具在初始渲染后并未显示在每个子级中。
答案 0 :(得分:0)
setRadioList
必须这样使用:
setRadioList(newList)
Spread运算符拆分数组并将每个值作为单独的参数发送,例如setRadioList(...[1,2,3])
会变成setRadioList(1, 2, 3)
,这当然是不正确的。
答案 1 :(得分:0)
操纵子代的代码不会突变原始子代,而是创建新子代,因此以下代码无效:
Children.map(children, (child, idx) => {
if (!isValidElement(child)) {return}
return cloneElement(child, {isExpanded: radioList[idx]})
});
尝试返回新的孩子,像这样:
export default (originalChildren, allowMultiple = true) => {
// 1) Setup initial list
const [radioList, setRadioList] = useState(Array(originalChildren.length).fill(false))
const [children, setChildren] = useState(originalChildren);
// 2) Map radioList values to component children on initial render, and do so again if radioList changes
useEffect(() => {
setChildren(children => Children.map(children, (child, idx) => {
if (!isValidElement(child)) {return}
return cloneElement(child, {isExpanded: radioList[idx]})
}));
}, [radioList])
// 3) Declare "toggle()" to modify the list that keeps track of what indexes are active
const toggle = useCallback((targetIndex) => {
setRadioList(radioList => radioList.map((item, idx) => {
if (allowMultiple) {
return targetIndex == idx ? !item : item
} else {
return targetIndex == idx ? !item : false
}
}))
}, [allowMultiple])
return { toggle, children }
}
// use like this: const { toggle, children } = useRadioList(children)