[英]Using context in react but they are not loading. I get TypeError: render is not a function
I am trying to use the state of users to display them in the posts page, but it does not render anything, I get an error "render is not a function".我正在尝试使用 state 用户在帖子页面中显示它们,但它不呈现任何内容,我收到错误“呈现不是函数”。 Any help is highly appreciated.
非常感谢任何帮助。 This is my front end
这是我的前端
This is my code:这是我的代码:
function PostsList(props) {
let { deletePosts } = useContext(PostsContext);
let users = useContext(UserContext);
let formatDate=(input)=>{
let v=new Date(input);
return v.toLocaleDateString("en-US")
}
return (
<PostsContext.Consumer value={users}>
<UserContext.Consumer>
{
({ posts }) => {
return <div>
<h3>welcome back, {users.name}</h3>
<a href="/posts/new"><button>Add New Post</button></a>
<div>
{posts.map((c) => {
console.log(posts)
return (
<div className='posts_list'>
<div key={c._id}>
</div>
<div className='posts_text'>
<h2>{c.name}</h2>
</div>
<div className='list'>
<Link to={`/edit/${c._id}`}>
<button>Edit</button>
</Link>
<button onClick={() => { deletePosts(c._id)}}>Delete</button>
<p>Tweet created on: {formatDate(c.createdAt)}</p>
</div>
</div>
)
})}
</div>
</div>
}
}
</UserContext.Consumer>
</PostsContext.Consumer>
);
}
export default PostsList;
The Consumer
component of a context is intended to be used in class components because we cannot use the useContext hook in a class component.上下文的
Consumer
组件旨在用于 class 组件,因为我们不能在 class 组件中使用 useContext 挂钩。 So, you could remove the Consumer as you are using the useContext
hook.因此,您可以在使用
useContext
挂钩时删除 Consumer。
You will have to wrap your PostList
component with the context providers somewhere in the parent like the following:您必须将
PostList
组件与父级某处的上下文提供程序一起包装起来,如下所示:
function App() {
return (
<UserContext.Provider value={someValue}>
<PostsContext.Provider value={someValue}>
<PostList />
</PostsContext.Provider>
</UserContext.Provider>
);
}
Then, you can use the context like the following:然后,您可以使用如下上下文:
function PostList() {
const users = useContext(UserContext);
// I am assuming you get posts from "PostsContext" itself
const { deletePosts, posts } = useContext(PostsContext);
const formatDate = (input) => new Date(input).toLocaleDateString("en-US")
return (
<div>
<h3>welcome back, {users.name}</h3>
<a href="/posts/new"><button>Add New Post</button></a>
<div>
{posts.map((c) => {
console.log(posts)
return (
<div className='posts_list'>
<div key={c._id}></div>
<div className='posts_text'>
<h2>{c.name}</h2>
</div>
<div className='list'>
<Link to={`/edit/${c._id}`}>
<button>Edit</button>
</Link>
<button onClick={() => { deletePosts(c._id)}}>
Delete
</button>
<p>
Tweet created on: {formatDate(c.createdAt)}
</p>
</div>
</div>
)
})}
</div>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.