等待redux加载数据
Wait for redux to load the data
我想从 redux 中提取一个对象。我想在加载时显示该值。我不知道怎么做。
const user = useSelector((state) => state.user);
这是我写的代码。它从 redux 中提取值,但最初是未定义的。我想在值完全加载时执行一个功能。我该怎么做?
您可以使用条件渲染来完成,例如:
const user = useSelector((state) => state.user);
{user && user.map(item=>(
<div>
<ul>
<li>{item.name}</li>
<ul>
</div>
)}
所以如果 user 为 true 则只映射 user 数组,在 JSX 的渲染方法中尝试此代码。
首先,reducer 状态是什么样的,如果你已经命名了 reducer 用户,并且在初始状态下有一个用户对象,那么你将不得不考虑使用
like this
const { user } = useSelector((state) => state.user);
or like this
const user = useSelector((state) => state.user.user);
then where you use it if the user is undefined
and you want to render the user object once the user data has successfully updated
something like
<div>
{user && user.name}
{user && user.age}
{user && user.height}
</div>
or if you want to show all the data and there are no embedded properties
you could do something like
<div>
{Object.keys(user).length > 0 &&
Object.keys(user)
.map((key) =>
<div>{user[key]}</div>)
}
</div>
我想从 redux 中提取一个对象。我想在加载时显示该值。我不知道怎么做。
const user = useSelector((state) => state.user);
这是我写的代码。它从 redux 中提取值,但最初是未定义的。我想在值完全加载时执行一个功能。我该怎么做?
您可以使用条件渲染来完成,例如:
const user = useSelector((state) => state.user);
{user && user.map(item=>(
<div>
<ul>
<li>{item.name}</li>
<ul>
</div>
)}
所以如果 user 为 true 则只映射 user 数组,在 JSX 的渲染方法中尝试此代码。
首先,reducer 状态是什么样的,如果你已经命名了 reducer 用户,并且在初始状态下有一个用户对象,那么你将不得不考虑使用
like this
const { user } = useSelector((state) => state.user);
or like this
const user = useSelector((state) => state.user.user);
then where you use it if the user is undefined
and you want to render the user object once the user data has successfully updated
something like
<div>
{user && user.name}
{user && user.age}
{user && user.height}
</div>
or if you want to show all the data and there are no embedded properties
you could do something like
<div>
{Object.keys(user).length > 0 &&
Object.keys(user)
.map((key) =>
<div>{user[key]}</div>)
}
</div>