我正在尝试创建一个页面,使用以下代码呈现 mongodb 服务器上的所有帖子:
constructor(props) {
super(props);
this.state = {
posts: []
}
this.listPosts = this.listPosts.bind(this);
}
componentDidMount() {
showAllPosts().then(res => {
console.log(res)
this.setState({
posts: res
})
})
console.log(this.state)
}
listPosts() {
this.state.posts.map(post =>
<listPost data={post}/>)
}
render() {
return (
<div>
<h1> All Posts </h1>
<ul class="mad-list">
{this.listPosts}
</ul>
</div>
)
}
如您所见,我在设置后并在函数之外使用 console.log() 记录状态,但第二个 console.log 显示一个空数组,所以我确定我的方式有问题我正在用这个设置状态。我读到您应该在函数外部创建一个名为 that 或 self 的变量,并将其设置为 this 并将其用于 .setState 函数,但我尝试了,但它仍然不起作用。我很确定没有帖子是导致我的 listPosts 功能无法工作的原因。
最佳答案
我认为更好的方法可能是
render() {
const {posts} = this.state;
let listPosts = (
posts.map(post => <listPost data={post}/>)
);
return (
<div>
<h1> All Posts </h1>
<ul class="mad-list">
{listPosts}
</ul>
</div>
)
}
我会解释我在这里做了什么。 因此,在 const {posts} 行中,我从您所在的州提取了帖子并将其存储在变量中。
此外,我将 map 保存在一个变量中,您可以直接在 JSX 代码中使用该变量。
我调用了在 JSX 中创建的变量来呈现内容。
这样你的函数 listPosts 就不再需要了,除非你除了循环结果之外还想做一些事情
关于javascript - 试图弄清楚为什么代码不会呈现列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826510/