【发布时间】: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