【发布时间】:2021-06-04 10:24:25
【问题描述】:
我的 React 和 Python 项目有问题,我正在从我的 API 中获取帖子并尝试在屏幕上显示它们,但我收到了这个错误:
错误:对象作为 React 子对象无效(找到:带有键 {Post} 的对象)。如果您打算渲染一组子项,请改用数组。
我正在使用一个额外的包来帮助我进行无限滚动,但它不起作用。我认为问题在于使用concat 方法。
当我向我的项目添加 POST 请求时,此问题开始出现,但这是一个 GET 请求,所以......
const Crypto = (props) => {
const [posts, setPosts] = useState([]);
const [skip, setSkip] = useState(0);
const [hasMore, setHasMore] = useState(true);
useEffect(() => {
loadFunc();
}, []);
const loadFunc = () => {
axios
.get(API_CRYPTO + skip)
.then((res) => {
if (res.data.messages.length === 0) {
setHasMore(false);
return;
}
setPosts(posts.concat(res.data.messages)); // here is the problem!
setSkip(skip + 20);
})
.catch((err) => {
// handle error
console.error(err);
});
};
return (
<InfiniteScroll
dataLength={posts.length} //This is important field to render the next data
next={loadFunc}
hasMore={hasMore}
loader={
<div className="spinner">
<PuffLoader color={"#ffcb6b"} size={50} />
</div>
}
scrollableTarget="scrollableDiv"
>
{posts.map((post) => (
<Post
channel_id={post.channel_id}
channel_pp={post.channel_image}
message={post.message_text}
channelName={post.channel_nickname}
timeStamp={post.message_ts}
moonCounter={post.likes}
messageImage={(post.photo_params || 0 || {}).photo_url}
postID={post._id.$oid}
key={post._id.$oid}
/>
))}
</InfiniteScroll>
);
};
这是我的Post 组件返回的内容:
<Card id="card">
<img src={Dots} alt="dots" className="dots"/>
<NavLink to={"/" + props.channel_id} style={{ textDecoration: 'none'}} className="pp-link">
<img src={props.channel_pp} alt="pp" className="pp" />
<p className="pp-user-name" to={"/" + props.channel_id}>{props.channelName}</p>
</NavLink>
<p className="time-elapsed">{postedAgo}</p>
{props.messageImage ? <img className="message-img" alt="message-img" src={props.messageImage} onClick={ModalHandler}/> : null}
<Linkify componentDecorator={componentDecorator}>
<p className="post-body">
{props.message}
</p>
</Linkify>
<div className="interact">
<Comment/>
<Moon moonCounter={props.moonCounter} postID={props.postID} />
</div>
</Card>
【问题讨论】:
-
请出示您的
Post组件 -
这只是
{posts.map((post) =>函数调用的错误语法吗?箭头指向一个开括号(而不是花括号{ -
如果不是,
res.data.messages的数据结构是什么?您可能会将posts状态的[] Array形式覆盖到一个对象中。 -
@ezhikov 它真的很长,但我刚刚更新了 JSX 返回。谢谢
-
您的
props.message中有什么内容?
标签: javascript python reactjs frontend