为什么我不能将函数的结果用作 useState 中的状态

Why I can't use result of function as a state in useState

我尝试将 useState 与对象数组一起用作值。像这样:

const [state, setState] = useState(arg)

Arg 是函数的结果,returns 一个这样的数组:

[{a:1, b:2}, {a:3, b:4}]

但是当我尝试使用它时,我的状态是空的,没有任何反应。如何在 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)
   }

添加了一小段代码

如果您使用lazy initial state,函数将只计算一次。

如果它在后续渲染中 returns 不同的值,其他值将被忽略。

const condition = false
const getArg = () => condition ? arg : []

useState(getArg) // getArg() will be called only once

不能直接使用useState。也许我的解决方案会有所帮助。我用 useEffect 传递了值。比如

useEffect(() => {
if (list)
  setList(yourFunc)
  )
}, [yourFunc])