【问题标题】:Updating data in material-table更新材料表中的数据
【发布时间】:2020-07-17 09:47:16
【问题描述】:

当我向表中添加数据时,它不会填充新记录。我创建了一个列表并显示它以查看它是否填充了新记录,它似乎已经在那里更新了。我在 componentWillReceiveProps 函数中添加了一个 console.log,以查看列表是否随新记录更新,列表确实会更新,但表永远不会更新。相当新的反应,不知道我错过了什么。

 import PropTypes from 'prop-types';
 import { connect } from 'react-redux';
 import { fetchPosts } from '../actions/postActions';
 import MaterialTable from 'material-table';

 class Posts extends Component {   
     componentWillMount() {
         this.props.fetchPosts();
     }

     componentWillReceiveProps(nextProps) {
         if(nextProps.newPost) {
             this.props.posts.unshift(nextProps.newPost);
         }
     }

     render () {
         const postItems = this.props.posts.map(post => (
             <div key={post.id}>
                 <h3>{post.title}</h3>
                 <p>{post.body}</p>
             </div>
         ));
         return (
           <div>
             <div>
                 <h1>Posts</h1>
                 {postItems}
             </div>
             <div style={{marginLeft:'15px',marginRight:'15px'}}>
             <div style={{ maxWidth: "100%" }}>
             <MaterialTable
               title="Users List"
               columns={[
                 { title: 'User Name', field: 'id' },
                 { title: 'Email', field: 'title' },                   
               ]}
               data={this.props.posts}
             />
             <br/><br/><br/>
           </div>
           </div>
           </div>
         );
     }
 }

 Posts.propTypes = {
     fetchPosts: PropTypes.func.isRequired,
     posts: PropTypes.array.isRequired,
     newPost: PropTypes.object
 }

 const mapStateToProps = state => ({
     posts: state.posts.items,
     newPost: state.posts.item
 });

 export default connect(mapStateToProps, { fetchPosts })(Posts);

【问题讨论】:

    标签: reactjs redux material-table


    【解决方案1】:

    您不能从组件内部设置道具,只能从外部设置。这就是 state 和 props 之间的区别(它在 React 中是非常基础的,请阅读它)。

    首先,在构造函数中初始化状态:

    constructor(props) {
      super(props);
    
      this.state = { posts: [] };
    }
    

    然后,当 props 改变时更新 state:

    componentWillReceiveProps(nextProps) {
             if(nextProps.newPost) {
                 let updatedPosts = this.state.props;
                 updatedPosts.unshift(nextProps.newPost);
                 this.setState({ posts: updatedPosts }); 
             }
         }
    }
    

    最后,使用表格中的状态:

    ...
    data={this.state.posts}
    ...
    

    【讨论】:

    • 不,我发布了代码。你在 props 更新时设置状态,componentWillReceiveProps
    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 2017-12-07
    • 2018-08-23
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多