我是新来的反应者。我创建了一个使用json url的新闻组件,然后吐出一些新闻文章。在客户端UI中,如果客户端更改json url,它将使用以下代码更新而不刷新页面:
componentDidUpdate(prevProps) {
if (prevProps.jsonUrl !== this.props.jsonUrl) {
this.getPosts();
}
}
但是,如果在客户端用户界面中更改了postCount:this.props.postCount,我还需要新闻提要进行动态更新。帖子数在下面的渲染方法中用于选择要显示的帖子数。
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;
答案 0 :(得分:1)
组件将自动对其道具的更改做出反应,因此无需将任何道具转移到状态。在这种情况下,如果postCount
是一个道具,则当它更改时,它将影响您共享以呈现组件的代码段。但是,我不知道posts
是否属于该州,在您的情况下应该属于该州,而您的方法getPosts
应该包含新帖子的setState。