laravel反应,表单提交后数据需要刷新

时间:2019-07-18 11:52:14

标签: reactjs laravel

我制作了一个具有2列section的组件。左边的是表格,右边的是显示数据库中的所有帖子。提交表单后,除非重新刷新,否则不会在右侧显示新插入的数据,有人可以帮忙吗? tkx

2 个答案:

答案 0 :(得分:0)

这很容易,将其存储到db中之后,从db / api发出请求即可获取所有相关记录并显示所有列表,并更新组件的状态。

答案 1 :(得分:0)

您需要在组件中使用componentWillReceiveProps(nextProps),并在componentWillReceiveProps中设置帖子状态,然后组件会自动重新呈现。

例如:

import React from 'react';

class Post extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.posts) {
      this.setState({ posts: nextProps.posts });
    }
  }

  render() {
    return (
      <div>
        {this.state.posts.map((post, index) => (
          <p>{post.title}</p>
        ))}
      </div>
    );
  }
}
const mapStateToProps = state => ({
  posts: state.posts,
});

export default Post;

注意:如果您的React版本低于17,则此方法有效

如果您使用的是最新版本的react,

componentDidUpdate将可以使用。这是comparison