React 16.3方法getDerivedStateFromProps使表单不可编辑

时间:2018-10-19 10:50:47

标签: reactjs redux crud

我有一个简单的React Redux CRUD应用程序,当使用componentWillReceiveProps生命周期方法编辑带有表单的条目时,该应用程序运行良好。最近想用componentWillReceiveProps方法代替它,该方法工作正常,这意味着编辑表单确实从需要编辑的帖子中提取了我们的数据,但现在该表单不可编辑。无法再将任何内容写入表单。这是起作用的先前代码:

state = {
  id: '',
  title: '',
  body: '',
  errors: {},
};
componentWillReceiveProps(nextProps, nextState) {
const { id, title, body } = nextProps.post;
console.log(`Next Props in Will Receive Props: ${nextProps.post.title}`);

this.setState({
  id,
  title,
  body,
});

}

这是我尝试将上面的代码替换为的代码:

static getDerivedStateFromProps(nextProps, prevState) {
const { id, title, body } = nextProps.post;
if (nextProps.post !== prevState.post) {
  return {
    id,
    title,
    body,
  };
}

return null;

}

这是表单代码:

  render() {
const { id, title, body, errors } = this.state;

return (
  <div className="add-post-from-container animated slideInLeft pt-5">
    <div className="card mb-3">
      <div className="card-header text-danger">
        <strong>Edit Post</strong>
      </div>
      <div className="card-body">
        <h5>Article ID: {id}</h5>
        <form onSubmit={this.onSubmit.bind(this)}>
          <div className="">
            <InputGroup
              name="title"
              type="text"
              placeholder="Enter Post Title"
              value={title}
              onChange={this.onChange}
              error={errors.title}
            />

            <div className="row">
              <div className="col-md-12">
                <InputTextarea
                  name="body"
                  value={body}
                  onChange={this.onChange}
                  error={errors.body}
                  placeholder="Enter Content"
                />
              </div>
            </div>
            <div className="mx-auto">
              <input
                type="submit"
                className="form-control form-control-lg btn btn-light mt-2"
                value="Update Post"
              />
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
);

请帮助我了解我在哪里出问题了。我对React / Redux很陌生。

2 个答案:

答案 0 :(得分:0)

您需要更改getDerivedStateFromProps方法代码,如下所示:

   static getDerivedStateFromProps(nextProps, prevState) {
       const { id, title, body } = nextProps.post;
       if (JSON.stringify(nextProps.post) !== JSON.stringify(prevState.post)) {
          return {
              id,
              title,
              body,
          };
       }

    return null;
 }

注意:我认为您未将状态保存为帖子,因此上述代码无效。您需要将帖子存储在状态中。

我个人认为,如果帖子ID是唯一的,最好比较ID而不是整个对象。示例代码如下所示:

  static getDerivedStateFromProps(nextProps, prevState) {
     const { id, title, body } = nextProps.post;
     if (nextProps.post.id !== prevState.id) {
       return {
         id,
         title,
         body,
       };
     }

return null;
}

答案 1 :(得分:0)

感谢Sawan的回答,但事实证明getDerivedStateFromProps不是我替换componentWillReceiveProps所需的方法。我需要的是componentDidUpdate。这是我要为其他像我这样迷失的灵魂发布的新代码...我将被替换的代码注释掉了...希望这对某人有帮助。

export class EditPost extends Component {
 static propTypes = {
 post: PropTypes.object.isRequired,
 editPost: PropTypes.func.isRequired,
 getPost: PropTypes.func.isRequired,
};



state = {
    id: '',
    title: '',
    body: '',
    errors: {},
  };
  // THE FOLLOWING WAS REPLACED
  // componentWillReceiveProps(nextProps, nextState) {
  //   const { id, title, body } = nextProps.post;
  //   console.log(`Next Props in Will Receive Props: ${nextProps.post.title}`);

  //   this.setState({
  //     id,
  //     title,
  //     body,
  //   });
  // }

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

  // THE FOLLOWING WAS USED TO REPLACE THE ABOVE COMMENTED OUT CODE
  componentDidUpdate(props, state, snapshot) {
    if (this.props.post !== props.post) {
      this.setState(this.props.post);
    }
  }