【问题标题】:How to update the user feed after updating the post?更新帖子后如何更新用户提要?
【发布时间】:2020-07-17 08:09:40
【问题描述】:

我有一个UserFeed 组件和EditForm 组件。编辑表单后,我需要立即重定向到UserFeed,更新后的数据应显示在UserFeed(帖子的标题和描述)上。

所以,流程就像-UserFeed,列出帖子,当点击编辑时,重定向到EditForm,更新字段,再次重定向到UserFeed,但现在UserFeed应该列出帖子使用更新的数据,而不是旧数据。

在这里,我只是重定向到 / 只是为了看看它是否有效。但我需要使用更新后的数据重定向到提要。

EditForm

import React, { Component } from "react";
import { connect } from "react-redux";
import { getPost } from "../actions/userActions"

class EditForm extends Component {
    constructor() {
    super();
    this.state = {
      title: '',
      description: ''
    };


    handleChange = event => {
        const { name, value } = event.target;
        this.setState({
            [name]: value
        })
    };

  componentDidMount() {
    const id = this.props.match.params.id
    this.props.dispatch(getPost(id))
  }

  componentDidUpdate(prevProps) {
    if (prevProps.post !== this.props.post) {
      this.setState({
        title: this.props.post.post.title,
        description: this.props.post.post.description
      })
    }
  }

  handleSubmit = () => {
    const id = this.props.match.params.id
    const data = this.state
    this.props.dispatch(updatePost(id, data, () => {
      this.props.history.push("/")
    }))
  }



  render() {
    const { title, description } = this.state
    return (
      <div>
        <input
          onChange={this.handleChange}
          name="title"
          value={title}
          className="input"
          placeholder="Title"
        />

        <textarea
          onChange={this.handleChange}
          name="description"
          value={description}
          className="textarea"
        ></textarea>

        <button>Submit</button>
      </div>
    );
  }
}

const mapStateToProps = store => {
  return store;
};

export default connect(mapStateToProps)(EditForm)

UserFeed

import React, { Component } from "react"
import { getUserPosts, getCurrentUser } from "../actions/userActions"
import { connect } from "react-redux"
import Cards from "./Cards"

class UserFeed extends Component {
  componentDidMount() {
    const authToken = localStorage.getItem("authToken")
    if (authToken) {
      this.props.dispatch(getCurrentUser(authToken))
      if (this.props && this.props.userId) {
        this.props.dispatch(getUserPosts(this.props.userId))
      } else {
        return null
      }
    }
  }

  render() {
    const { isFetchingUserPosts, userPosts } = this.props
    return isFetchingUserPosts ? (
      <p>Fetching....</p>
    ) : (
      <div>
        {userPosts &&
          userPosts.map(post => {
            return <Cards key={post._id} post={post} />
          })}
      </div>
    )
  }
}

const mapStateToPros = state => {
  return {
    isFetchingUserPosts: state.userPosts.isFetchingUserPosts,
    userPosts: state.userPosts.userPosts.userPosts,
    userId: state.auth.user._id
  }
}

export default connect(mapStateToPros)(UserFeed)

Cards

import React, { Component } from "react"
import { connect } from "react-redux"
import { compose } from "redux"
import { withRouter } from "react-router-dom"

class Cards extends Component {

  handleEdit = _id => {
    this.props.history.push(`/post/edit/${_id}`)
  }

  render() {
    const { _id, title, description } = this.props.post
    return (
      <div className="card">
        <div className="card-content">
          <div className="media">
            <div className="media-left">
              <figure className="image is-48x48">
                <img
                  src="https://bulma.io/images/placeholders/96x96.png"
                  alt="Placeholder image"
                />
              </figure>
            </div>
            <div className="media-content" style={{ border: "1px grey" }}>
              <p className="title is-5">{title}</p>
              <p className="content">{description}</p>
              <button
                onClick={() => {
                  this.handleEdit(_id)
                }}
                className="button is-success"
              >
                Edit
              </button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    nothing: "nothing"
  }
}

export default compose(withRouter, connect(mapStateToProps))(Cards)

updatePost 操作

export const updatePost = (id, data, redirect) => {
    return async dispatch => {
      dispatch( { type: "UPDATING_POST_START" })
      try {
      const res = await axios.put(`http://localhost:3000/api/v1/posts/${id}/edit`, data)
      dispatch({
        type: "UPDATING_POST_SUCCESS",
        data: res.data
      })
      redirect()
    } catch(error) {
      dispatch({
        type: "UPDATING_POST_FAILURE",
        data: { error: "Something went wrong"}
      })
    } 
  }
  }

我不确定我的行为是否正确。

这是 updatePost 控制器

updatePost: async (req, res, next) => {
    try {
      const data = {
        title: req.body.title,
        description: req.body.description
      }
      const post = await Post.findByIdAndUpdate(req.params.id, data, { new: true })
      if (!post) {
        return res.status(404).json({ message: "No post found "})
      }
      return res.status(200).json({ post })
    } catch(error) {
      return next(error)
    }
}

【问题讨论】:

    标签: node.js reactjs express redux react-redux


    【解决方案1】:

    一个错误是设置当前字段需要在 mongodb 中使用 $set ,同时还想构建对象,例如如果 req.body 没有 title 则会产生错误

    updatePost: async (req, res, next) => {
        try {
          const data = {};
            if(title)  data.title=req.body.title;
            if(description)  data.description=req.body.description
          const post = await Post.findByIdAndUpdate(req.params.id, {$set:data}, { new: true })
          if (!post) {
            return res.status(404).json({ message: "No post found "})
          }
          return res.status(200).json({ post })
        } catch(error) {
          return next(error)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 2013-12-21
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2020-07-04
      • 2020-08-10
      相关资源
      最近更新 更多