如何从 useSelector 初始化 useState

时间:2021-05-06 16:18:32

标签: reactjs react-native react-redux react-hooks

如果 userDetails?.needUserDetails === true,我只想显示Modal。
我正在尝试从 useSelector 初始化 useState,但我可以看到它以 null 开始。 我还尝试将默认参数传入 showModal 并尝试使用 useEffect() 来初始化 setShowModal(userDetails?.needUserDetails)

const userDetails = useSelector((state) => state.users.userDetails);
const userDetailsLoading =  useSelector((state) => state.users.userDetailsLoading);
const [showModal, setShowModal] = useState(userDetails?.needUserDetails);

return ({userDetailsLoading ? (
        <Spinner>
      ) : (
        <ShowModal
              showModal={showModal}
              needUserDetails={userDetails.needUserDetails}
              setShowModal={setShowModal}
            />
)
const ShowModal = ({
  needUserDetails,
  showModal = needUserDetails,
  setShowModal,
}) => {
  return (<Modal visible={showModal} onDismiss={() => setShowModal(false)})
}


从 useSelector 初始化 useState 的最佳方法是什么?应该避免这种情况吗?有哪些替代方案?

1 个答案:

答案 0 :(得分:0)

您的初始状态 state.users.userDetails.needUserDetails 似乎未设置。 所以你基本上一切都做对了,但你的初始值没有设置。

好的,所以最初您的 userDetails?.needUserDetails 将被设置为 null,因为您还没有获取 userDetails(如果总是这样,那么您甚至可能不需要通过初始价值)。收到后,您的组件将重新呈现,因为 useSelector 将触发它。并且我们可以使用Effect钩子,监听userDetails?.needUserDetails来设置值

哦,好的,试试下面的代码,你也可以去掉严格相等,如果你不需要它:

const userDetails = useSelector((state) => state.users.userDetails);
const userDetailsLoading =  useSelector((state) => state.users.userDetailsLoading);
const [showModal, setShowModal] = useState(userDetails?.needUserDetails === true);

useEffect(() => {
     setShowModal(userDetails?.needUserDetails === true)
}, [userDetails?.needUserDetails])

return ({userDetailsLoading ? (
        <Spinner>
      ) : (
        <ShowModal
              showModal={showModal}
              needUserDetails={userDetails.needUserDetails}
              setShowModal={setShowModal}
            />
)