[英]Why I can't use result of function as a state in useState
我尝试使用带有对象数组的useState
作为值。 像这样的东西:
const [state, setState] = useState(arg)
Arg 是 function 的结果,它返回如下数组:
[{a:1, b:2}, {a:3, b:4}]
但是当我尝试使用它时,我的 state 是空的,没有任何反应。 如何在useState
中使用 arg? 我看到另一个类似的问题,但这些解决方案不起作用。 或者我不明白。
//take users list from DB const dispatch = useDispatch() const items = useSelector((state) => state.users.list) useEffect(() => { dispatch(funcThatGetUsersList) }, [dispatch]) //use items for handler const [list, setList] = useState([]) function checkboxHandler = (event) => { do smth with setList(list) }
添加了一小段代码
如果您使用惰性初始 state ,则 function 将仅评估一次。
如果它在后续渲染中返回不同的值,那些其他值将被忽略。
const condition = false
const getArg = () => condition ? arg : []
useState(getArg) // getArg() will be called only once
你不能直接使用 useState 。 也许我的解决方案会有所帮助。 我用 useEffect 传递了这个值。 如
useEffect(() => {
if (list)
setList(yourFunc)
)
}, [yourFunc])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.