更新post计数反应方式
Updating post count the reactive way
我是新手。我创建了一个新闻组件,它使用 json url 然后吐出一些新闻文章。在客户端 UI 如果客户端更改 json url 它将更新而不刷新页面使用此代码:
componentDidUpdate(prevProps) {
if (prevProps.jsonUrl !== this.props.jsonUrl) {
this.getPosts();
}
}
但是,如果 postCount: this.props.postCount 在客户端 UI 发生变化,我还需要动态更新。 post 计数在下面的渲染方法中用于选择显示多少 post。
posts
.slice(0, postCount)
.map(post => {
// Variables to use
let { id, name, summary, url, imgUrl} = post;
// Stripping html tags from summary
//let strippedSummary = summary.replace(/(<([^>]+)>)/ig,"");
// What we actually render
return (
<div key={id} className={ styles.post}>
<p>{name}</p>
{/* <p>{summary}</p> */}
<a href={url}>{url}</a>
<img className={ styles.postImage} src={imgUrl} />
</div>
);
})
非常感谢任何帮助! - 我在 componentDidUpdate:
里面想这样的事情
if (prevProps.postCount !== this.props.postCount) {
this.setState( this.state.postCount; );
}
编辑:
我现在使用道具中的 postCount 而不是状态,它会立即更新! :D
// Grabbing objects to use from state
const { posts, isLoading } = this.state;
const { postCount } = this.props;
组件将自动对其 props 的变化做出反应,因此无需将任何 props 转移到状态。在这种情况下,如果 postCount
是一个道具,当它发生变化时,它应该会影响您共享的用于呈现组件的代码段。但是,我不知道 posts
是否是状态的一部分,在你的情况下它应该是并且你的方法 getPosts
应该使用新帖子设置状态。
我是新手。我创建了一个新闻组件,它使用 json url 然后吐出一些新闻文章。在客户端 UI 如果客户端更改 json url 它将更新而不刷新页面使用此代码:
componentDidUpdate(prevProps) {
if (prevProps.jsonUrl !== this.props.jsonUrl) {
this.getPosts();
}
}
但是,如果 postCount: this.props.postCount 在客户端 UI 发生变化,我还需要动态更新。 post 计数在下面的渲染方法中用于选择显示多少 post。
posts
.slice(0, postCount)
.map(post => {
// Variables to use
let { id, name, summary, url, imgUrl} = post;
// Stripping html tags from summary
//let strippedSummary = summary.replace(/(<([^>]+)>)/ig,"");
// What we actually render
return (
<div key={id} className={ styles.post}>
<p>{name}</p>
{/* <p>{summary}</p> */}
<a href={url}>{url}</a>
<img className={ styles.postImage} src={imgUrl} />
</div>
);
})
非常感谢任何帮助! - 我在 componentDidUpdate:
里面想这样的事情if (prevProps.postCount !== this.props.postCount) {
this.setState( this.state.postCount; );
}
编辑:
我现在使用道具中的 postCount 而不是状态,它会立即更新! :D
// Grabbing objects to use from state
const { posts, isLoading } = this.state;
const { postCount } = this.props;
组件将自动对其 props 的变化做出反应,因此无需将任何 props 转移到状态。在这种情况下,如果 postCount
是一个道具,当它发生变化时,它应该会影响您共享的用于呈现组件的代码段。但是,我不知道 posts
是否是状态的一部分,在你的情况下它应该是并且你的方法 getPosts
应该使用新帖子设置状态。