React 中的初始状态

Initial state in React

我需要在 render() 之前从服务器下载数据并用 HTML.I 覆盖它有错误 this.state.news is undefinded。我尝试了 getInitialStatecomponentWillMount 的示例,但它不起作用。

import { Component } from 'react'

import { Link } from 'react-router-dom'
import $ from 'jquery'

export default class News extends Component{
constructor(props){
    super(props);
    this.state = { news: []};
}

componentWillMount() {
    const setState = this.setState;
    $.ajax({
        type: "GET",
        url: "localhost/news",
        data: {},
        success: function(data){
            setState(() => data);
        },
    });
}

render(){
    let news = this.state.news;
    return(
        news.map(function(n, i){
            return <div class="news-block">
                <Link to={`/news/post/${n.id}`}><h5>{n.theme}</h5></Link>
                <small>
                    <Link to={`/user/${n.author}`}>
                        {n.author}
                    </Link>, {n.date_of_create}
                </small>
                <p>{n.about}</p>
            </div>;
        })
    );
}
}

来自 ajax 请求的 json 示例:

 {
  "news": [
    {
      "id": "35268",
      "theme": "The,e",
      "author": "alex",
      "date_of_create": "2000-01-01 00:00:54",
      "public": "0",
      "about": "sometjing",
      "source": "some news"
    }
   ]
   }

我认为你的代码有几个问题。

第一个是,当您处理异步数据时,您正在以同步方式获取数据。

另一个是您正在访问您所在州的“新闻”属性,但从未分配过它。

你应该尝试这样的事情:

import { Component } from 'react'

import { Link } from 'react-router-dom'
import $ from 'jquery'

export default class News extends Component{
constructor(props){
    super(props);
    this.getNews = this.getNews.bind(this);
}

componentWillMount() {
    const setState = this.setState.bind(this);
    $.ajax({
        type: "GET",
        url: "localhost/news",
        data: {},
        success: function(data){
            setState(() => data);
        },
    });
}

render(){
    let news = this.state.news;
    return(
        news.map(function(n, i){
            return <div class="news-block">
                <Link to={`/news/post/${n.id}`}><h5>{n.theme}</h5></Link>
                <small>
                    <Link to={`/user/${n.author}`}>
                        {n.author}
                    </Link>, {n.date_of_create}
                </small>
                <p>{n.about}</p>
            </div>;
        })
    );
}
}