如何从useSelector初始化useState



如果userDetails?,我只想显示Modal?。needUserDetails===true
我正试图从useSelector初始化useState,但我可以看到它一开始是null。我还尝试将默认参数传递到showModal中,并尝试使用Effect((初始化setShowModal(userDetails?.reneedUserDetails(

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的最佳方法是什么?应该避免这种情况吗?有哪些替代方案?

看起来您的初始状态state.users.userDetails.needUserDetails没有设置。所以你基本上把每件事都做对了,但你的初始值没有设定。

好的,所以最初您的userDetails?.needUserDetails将被设置为null,因为您还没有获取userDetails(如果总是这样,那么您可能甚至不需要传递初始值(。一旦收到它,你的组件将被重新渲染,因为useSelector将触发它。我们可以使用Effect hook,监听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}
/>
)

相关内容

  • 没有找到相关文章