React Redux工具包
我有Postsslice,可从服务器提供有关帖子的数据 在此处输入图像描述
PostSlice Code
const initialState = {
posts: [],
};
const post = createSlice({
name: "post",
initialState,
reducers: {
getPosts(state, action) {
state.posts = action.payload.posts;
},
},
});
const { getPosts } = post.actions;
export function GetPostByInterests() {
return async (dispatch) => {
try {
const response = await API.get("/posts", {
params: {
limit: 10,
offset: 0,
},
});
const data = response.data;
const posts = data.data;
dispatch(
getPosts({
posts: posts,
})
);
} catch (e) {}
};
}
我正在尝试在前端拉出用户的图像在明信片中,我会收到一个错误:undurect typeError:posts.author.avatar是未定义的
前端代码
export const News = () => {
const dispatch = useDispatch();
const posts = useSelector((state) => state.post.posts);
useLayoutEffect(() => {
dispatch(GetPostByInterests());
}, []);
return (
<div className="container-md shadow-lg bg-white py-10 px-8 mx-[5rem] my-[1rem] rounded-md">
{posts.map((posts) => (
<PostCard key={posts.id} posts={posts} />
))}
</div>
);
};
明信片前端图像显示:
<img
className="w-12 h-12 rounded-full object-cover mr-4 shadow"
src={posts.author.avatar.url}
alt="avatar"
></img>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
welcom to stackoverflow @memphis
您需要使用在
src
的img
标签中。像这样:最好使用映射来自API的数据时,以避免获取数据时遇到未定义的错误:
Welcom to Stackoverflow @memphis
You need to use Optional Chaining in the
src
of theimg
tag. Like this:It's also good practice to use a Ternary Operator when mapping through the data that is coming from the API, in order to avoid getting undefined errors when the data is being fetched: