Javascript 试图找出code获胜的原因';t渲染列表

Javascript 试图找出code获胜的原因';t渲染列表,javascript,reactjs,state,Javascript,Reactjs,State,我正在尝试制作一个页面,用以下代码呈现我在mongodb服务器上的所有帖子: constructor(props) { super(props); this.state = { posts: [] } this.listPosts = this.listPosts.bind(this); } componentDidMount() { showAllPosts().then(res =

我正在尝试制作一个页面,用以下代码呈现我在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>
        )
    }
构造函数(道具){
超级(道具);
此.state={
员额:[]
}
this.listPosts=this.listPosts.bind(this);
}
componentDidMount(){
showAllPosts()。然后(res=>{
console.log(res)
这是我的国家({
职位:res
})
})
console.log(this.state)
}
listPosts(){
this.state.posts.map(post=>
)
}
render(){
返回(
所有职位
    {this.listPosts}
) }

正如您所看到的,我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>
 )
}
render(){
const{posts}=this.state;
让listPosts=(
posts.map(post=>)
);
返回(
所有职位
    {listPosts}
) }
我会解释我在这里做了什么。 因此在const{posts}行中,我从您的状态中提取posts并将其存储在变量中

另外,我将映射保存在一个变量中,您可以直接在JSX代码中使用该变量

我调用了在JSX中创建的变量来呈现内容


这样,您就不再需要函数listPosts,除非您想做一些事情,而不是遍历结果您忘了运行函数:
{This.listPosts()}
React组件名称需要大写:
ListPost
第二个
控制台.log(This.state)
实际上是首先运行的,在
showAllPosts()
可以做任何事情之前,它总是记录初始状态:
{posts:[]}
除了marzelin提到的之外,您还忘记了listPosts()中的“return”。我会考虑创造性的乔的答案,因为它是更多的IdoMy反应。“类ListPoST扩展Realth.组件{构造器(道具){Super(道具)”;Test.t= {用户名:``,标题:``,BooTyth:`}}组件IDuxMug(){StStand(StStand){username:this.props.data.username,title:this.props.data.title,bodytext:this.props.data.bodytext}}render(){return({this.state.title}{this.state.username}{this.state.bodytext}

)}导出默认ListPost;当我将所有内容更改为您告诉我的内容时,它仍然不会打印出我已导入ListPost的ul组件中的任何ListPost组件。您能想到这不起作用的原因吗?您是否将ListPost作为您在该组件中导入或声明的组件?