I have made a component with 2 column section . left one is form and right one show all posts from db. after submitting form new inserted data doesn't show in right section unless I refresh, can anybody help? tkx
You need to use componentWillReceiveProps(nextProps)
in your component and set your posts state in componentWillReceiveProps
and automatically your component will re-render.
For example:
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;
Note: This will work if your React version is less than 17
componentDidUpdate
will work if you are using most latest version of react. Here is the comparison
这很容易,在存储到db中之后,从db / api发出请求可以获取所有相关记录并显示所有列表,并更新组件的状态。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.