如何在react

时间:2018-10-08 00:18:00

标签: reactjs firebase axios

我浏览了许多this之类的文章和帖子,但不适用于我的情况。我只需要使用axios从我的应用程序的帖子列表中删除一个项目。在axios文档中,它说您需要将参数传递给delete方法。另外,在大多数应用程序中,我都使用过ID,而ID却没有处于状态。但是我不能让它工作。请查看我的整个代码。我知道我的删除方法有误,请帮助我修复它:

    // The individual post component
    const Post = props => (
    <article className="post">
        <h2 className="post-title">{props.title}</h2>
        <hr />
        <p className="post-content">{props.content}</p>
        <button onClick={props.delete}>Delete this post</button>
    </article>
);

// The seperate form component to be written later

class Form extends React.Component {}

// The posts loop component

class Posts extends React.Component {
    state = {
        posts: [],
        post: {
            title: "",
            content: ""
        }
        // error:false
    };

    componentDidMount() {
        const { posts } = this.state;
        axios
            .get("url")
            .then(response => {
            const data = Object.values(response.data);
            this.setState({ posts : data });
            });
    }
    handleChange = event => {
        const [name , value] = [event.target.name, event.target.value];
        // const value = event.target.value;
        const { post } = this.state;
        const newPost = {
            ...post,
            [name]: value
        };
        this.setState({ post: newPost });
    };

    handleSubmit = event => {
        event.preventDefault();
        const {post} = this.state;
        const {posts} = this.state;
        axios
            .post("url", post)
            .then(response => {
            // console.log(response);
            const newPost = Object.values(response.data);
            this.setState({ post: newPost });
            const updatedPosts =  [...posts, {title:post.title,content:post.content}];
            this.setState({ posts: updatedPosts});
            // console.log(post);
            console.log(updatedPosts);
            console.log(this.state.posts);
            });
    };

    handleDelete = () => {
        const { post } = this.state;
        axios.delete("url",{params: {id: post.id}})
        .then(response => {
            console.log(response);
        });
    };

    render() {
        let posts = <p>No posts yet</p>;
        if (this.state.posts !== null) {
            posts = this.state.posts.map(post => {
                return <Post 
                                 key={post.id} 
                                 {...post}
                                 delete={this.handleDelete}/>;
            });
        }

        return (
            <React.Fragment>
                {posts}
                <form className="new-post-form" onSubmit={this.handleSubmit}>
                    <label>
                        Post title
                        <input
                            className="title-input"
                            type="text"
                            name="title"
                            onChange={this.handleChange}
                        />
                    </label>
                    <label>
                        Post content
                        <input
                            className="content-input"
                            type="text"
                            name="content"
                            onChange={this.handleChange}
                        />
                    </label>
                    <input className="submit-button" type="submit" value="submit" />
                </form>
            </React.Fragment>
        );
    }
}

我还在控制台中看到此错误: 未捕获(承诺)TypeError:无法将未定义或null转换为对象 在get方法中的Function.values处。 再次感谢。

2 个答案:

答案 0 :(得分:4)

您没有指定Post组件应删除的内容。换句话说,props.delete没有收到id传递给您的父组件。为此,您可以将其更改为() => props.delete(props.id),然后在父组件中,需要让handleDelete方法接收要定位的项目的id,即id是我们早些时候从Post离开的。

我不知道您的服务器是如何设置的,但是使用您最初在问题中遇到的axios请求,您的代码将如下所示:

handleDelete = (itemId) => {
    // Whatever you want to do with that item
    axios.delete("url", { params: { id: itemId } }).then(response => {
      console.log(response);
    });

这是CodeSandbox(在构造函数中使用一些伪数据),它显示正在console.log()中传递的项目(axios语句已被注释掉)。


编辑:如何使用Firebase REST API进行axios删除请求

抱歉,我没有看到您使用的是Firebase。直接REST请求与Firebase有所不同。在您的配置中,请求应如下所示:

axios.delete(`${url}/${firebasePostId}.json`).then(response => {
    console.log(response)
})

这是假设您的Firebase规则允许未经授权的请求(强烈建议您这样做,因为有人可以发送此请求)。

请注意,firebasePostId是Firebase在向他们发送POST请求时提供的按键,实际上,id是您帖子的不错选择。您在评论中提到的-LOLok8zH3B8RonrWdZs就是一个例子。

有关Firebase REST API语法的更多信息,请查看其documentation

答案 1 :(得分:0)

感谢@FranklinFarahani。由于时间太长,我不得不写一个答案。我已经更改了我的get和post方法,并设法解决了delete方法。我使用firebase为每个帖子创建的唯一键来删除每个项目。我得到了那个inget方法。这是完整的代码。

 // The individual post component
  const Post = props => (
    // use the key as an id here
    <article id={props.id} className="post">
        <h2 className="post-title">{props.title}</h2>
        <hr />
        <p className="post-content">{props.content}</p>
        <button onClick={props.delete}>Delete this post</button>
    </article>
);

// The Post lists component

class Posts extends React.Component {
    state = {
        posts: [],
        post: {
            id: "",
            title: "",
            content: ""
        },
        indexes: []
    };

    componentDidMount() {
        const { posts } = this.state;
        axios
            .get("firebaseURL/posts.json")
            .then(response => {
              // create an array to hold th unique id as key and post as value using Object.entries
                const retrievedPosts = [];
                for (const [key, value] of Object.entries(response.data)) {
                    const post = {
                        id: key,
                        title: value.title,
                        content: value.content
                    };
                    // add allposts to the array here
                    retrievedPosts.push(post);
                }
                // update state
                this.setState({ posts: retrievedPosts });
            console.log(retrievedPosts);
            });
    }
    handleChange = event => {
        const [name, value] = [event.target.name, event.target.value];
        // const value = event.target.value;
        const { post } = this.state;
        const newPost = {
            ...post,
            [name]: value
        };
        this.setState({ post: newPost });
    };


    handleSubmit = event => {
        event.preventDefault();
        const { posts } = this.state;
        // use this as a temporary id for post method
        const postIndex = posts.length + 1;
        const post = {
            id: postIndex,
            title: this.state.post.title,
            content: this.state.post.content
        };
        axios
            .post("firebaseURL/posts.json", post)
            .then(response => {
                const updatedPosts = [
                    ...posts,
                    { id: post.id, title: post.title, content: post.content }
                ];
            // update state
                this.setState({ posts: updatedPosts });
            console.log(posts);
            });

    };

    handleDelete = postId => {
        event.preventDefault();
        // get a copy of the posts
        const posts = [...this.state.posts];
        // in delete method use postId to create a unique url for the post to be deleted
        axios
            .delete(
                "firebaseURL/posts/" + postId + ".json"
            )
            .then(response => {
            //update state
                this.setState({ posts: posts });
            });
    };

    render() {
        let posts = <p>No posts yet</p>;
        if (this.state.posts !== null) {
            posts = this.state.posts.map(post => {
                return (
                    <Post
                        id={post.id}
                        key={post.id}
                        {...post}
                        delete={() => this.handleDelete(post.id)}
                    />
                );
            });
        }

        return (
            <React.Fragment>
                {posts}
                <form className="new-post-form" onSubmit={this.handleSubmit}>
                    <label>
                        Post title
                        <input
                            className="title-input"
                            type="text"
                            name="title"
                            onChange={this.handleChange}
                        />
                    </label>
                    <label>
                        Post content
                        <textarea
                            className="content-input"
                            rows="7"
                            type="text"
                            name="content"
                            onChange={this.handleChange}
                        />
                    </label>
                    <input className="submit-button" type="submit" value="submit" />
                </form>
            </React.Fragment>
        );
    }
}

问题是删除后我的状态没有更新,因此尽管该帖子已从我的数据库中删除,但仍在DOM中。

更重要的是,如果提交新帖子后获取请求或刷新完成后无法将其删除。原因是在发布请求后,密钥将在请求完成后创建,因此直到下一个get请求或刷新之后,我才拥有更新状态和DOM的密钥。该ID将是我在发布方法期间分配的临时ID,该ID不能用于删除帖子。