mern-更新后的值在数据中为空

问题描述

我正在尝试更新帖子。后端中的PUT请求工作正常,返回200并在Postman上进行测试时更新帖子,但是当我尝试更新前端中的帖子(反应)时,我没有收到任何错误,但是更新的帖子没有被执行提交时更新,并且更新的字段(标题和正文)为空。当我在前端console.log(data)时更新的值为空,这就是为什么不将其发送到背面的原因结束,但它们正确显示在post中。 为什么更新后的值null位于data中?如何使用新值更新帖子,而不是获取空值?

data:

data

post:

post

更新的代码:前端

const EditPost = ({match}) => {
  const [values,setValues] = useState({
    title: "",body: "",error: ""
  });
  
  const [post,setPost] = useState({});
  const { user,token } = isAuthenticated();
  const {
    title,body,error,} = values;


  const init = (id) => { 
      read(id).then(data => {
if (data.error) {
    setValues({...values,error: data.error})
} else {
    setValues({...values,title: data.title,body: data.body,}) 
    setPost({title: values.title,body: values.body})
     }
    })
}
 

useEffect(() => {
    const id = match.params.id;
  init(id);
},[]);

useEffect(() => {
  setPost({...values });
},[values.title,values.body]);


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

  const clickSubmit = (event) => {
    event.preventDefault();
    setValues({ ...values,error: "" });

    editPost(match.params.userId,match.params.id,token,post).then((data) => {
      if (data.error) {
        setValues({ ...values,error: data.error });
      } else {
        setValues({
          ...values,title: "",error: false,});      
      console.log(post)
      console.log(data)
      }
    });
  };

  const newPostForm = () => (
    <form onSubmit={clickSubmit}>
      <div>
        <input
          onChange={handleChange("title")} type="text"
          name="title"
          value={title}
        />
      </div>

      <div className="form-group">
        <textarea
          onChange={handleChange("body")}
          value={body} name="body"
        />
      </div>

      <button type="submit">Publish</button>
    </form>
  );
  const showError = () => (
    <div
      style={{ display: error ? "" : "none" }}>
      {error}
    </div>
  );

  return (
        <div>  
          {showError()}
          {newPostForm()}
        </div>
  );
};

export default EditPost;
export const editPost = (userId,id,post) => {
    return fetch(`${API}/${userId}/${id}/edit`,{
        method: 'PUT',headers: {
            Accept: 'application/json',Authorization: `Bearer ${token}`
        },body: JSON.stringify(post)
    })
        .then(response => {
            return response.json();
            
        })
        .catch(err => console.log(err));
};

postsByUser.js

 <Link className="mypost_btn edit_btn" to={`/${_id}/${post._id}/edit`}>
     Edit
 </Link>

后端代码

exports.edit = (req,res) => {
  if (!ObjectID.isValid(req.params.id))
        return res.status(400).send(`ID is not valid: ${req.params.id}`)

  const {title,body} = req.body

  const updatedPost = {title,body }

  Post.findByIdAndUpdate(req.params.id,{
    $set: updatedPost
  },{new:true},(error,data) => {
    if (error) {
      return error
    } else {
      res.send(data)
      console.log(data)
    }
  })
}

解决方法

您的问题就在这里

editPost(match.params.userId,match.params.id,token,post)

post未定义。

由于未定义post,因此不会传递任何数据。因此,titlebody等于null。根据我在代码中看到的内容,您需要做的是定义一个名为post的状态变量。我认为您打算这样做:

const [post,setPost] = useState({values.title,values.body});

然后确保您的values使用useEffect()进行更改时都会更新您的帖子,

useEffect(() => {
   setPost({...values });
},[values.title,value.body]);

因此,当您调用editPost() http-put-method时,发布中便有一个value。而且应该可以。

,

在EditPost.js import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.neo4j.ogm.config.Configuration; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.springframework.util.StringUtils; public class PoCTest { private static SessionFactory ogmSessionFactory; @BeforeAll private static void createSessionFactory() { final Configuration config = new Configuration.Builder().uri( "bolt://localhost:7687" ) .credentials( "neo4j","blahblahblah..." ) .useNativeTypes() .verifyConnection( true ) .build(); ogmSessionFactory = new SessionFactory( config,PoCTest.class.getPackageName() ); } private static Session getOgmSession() { return ogmSessionFactory.openSession(); } @Test void testCreateCarChangeDriver() { final Car car = new Car(); final Person fred = new Person(); fred.setName( "fred" ); car.setDriver( fred ); // sets the relationship as expected getOgmSession().save( car ); // saves the relationship as expected assertEquals( "fred",getOgmSession().load( Car.class,car.getId() ).getDriver().getName() ); // passes car.setDriver( null ); // then we clear the relationship ("fred" is no longer the driver) getOgmSession().save( car ); // then *save* it... _but_... // Bug! The save ^ has *not* cleared the relationship... assertNull( getOgmSession().load( Car.class,car.getId() ).getDriver() ); // <- and this line fails! } } 中,您缺少第四个参数,它是您自己发送的要更新的“发布”

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...