我是 React Native 的初学者。我被卡住了,因为我无法创建一个调用函数 lis = ['a','b','c','d']
for a in lis:
print(a + 'x')
的按钮,该函数将删除 blogPosts 数组中的最后一个元素。我想使用 useState 钩子来删除元素。如果有人能帮我解决这个问题,那将会很有帮助。代码如下:
BlogContext.js
delBlogPost
这是我创建要删除的按钮的地方。就像添加博客帖子按钮一样,我想使用 useState 删除帖子按钮。
IndexScreen.js
import React, {useState} from 'react';
const BlogContext = React.createContext();
export const BlogProvider = ({ children }) => {
const [blogPosts, setBlogPosts] = useState([]);
const addBlogPost = () => {
setBlogPosts([...blogPosts, {title: `Blog Post #${blogPosts.length+1}`}]);
};
{/* I want to create a delBlogPost function here which would delete the last element in array of objects*/}
const delBlogPost = () => {
};
return (
<BlogContext.Provider value={{data: blogPosts, addBlogPost, delBlogPost }}>
{children}
</BlogContext.Provider>
);
};
export default BlogContext;
答案 0 :(得分:0)
useState 钩子返回一个值数组。第一个元素始终是值,而第二个值始终是 setter 函数。使用 useState 的状态值是不可变的,不能直接修改,这就是为什么给你一个 setter。考虑到这一点,您的 addBlogPost
和 delBlogPost
代码应如下所示。
const [blogPosts, setBlogPosts] = React.useState([])
// since state is immutable, we can only set the value and not directly modify it
// we use the ... operator to add the current posts and then tack the new one at
// the end.
const addBlogPost = (blogPostToAdd) => setBlogPost([ ...blogPosts, blogPostToAdd])
const delBlogPost = (blogPostToRemove) => {
const blogPostsWithRemoved = blogPosts.filter((blogPost) => {
// you do not have to use id to identify which blog post you are removing,
// but you have to use something to identify the blog post you want to remove
return blogPost.id !== blogPostToRemove.id
})
}
现在,当您使用这些函数时,您实际上需要将博客文章对象传递给它们。
<Button onClick={(event) => {
addBlogPost(blogPost)
}}>
Click Me to Add
</Button>