React - 渲染 JSON 数据时为空数组

React - Empty Array When Rendering JSON Data

为什么渲染这个 JSON 数组时会创建一个空数组? See attached screenshot 我假设构造函数只是用空值启动它并在稍后填充它。

Javascript + React 的新手,只是想确保我了解正在发生的事情。我也将接受对下面垃圾代码的批评。 Codepen link

class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>
      <ul key={job.id}> 
        <div class="company">{job.company_name}</div>
        <div class="title">{job.title}</div>
      </ul>
    );
    return(
      <div>{formattedJobs}</div>
    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (
    <div className="app">
      <div className="header">
        <h1 id="header-title">Job Postings</h1>
      </div>
      <div className="content">
        <Jobs jobs={this.state.jobs}/>
      </div>
    </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

您正在从 ajax 异步请求中获取作业。这就是为什么初始值是一个空数组。

App.render 在您的 ajax 请求完成之前执行,这就是为什么您没有向作业组件提供任何作业的原因。 ajax 完成后,作业数组将填充结果并发送到作业组件以呈现该 ajax 请求的结果。

始终在 ComponentDidMount 中使用 fetch 语句,因为它会在您的组件首次呈现后立即调用

ComponentDidMount {
 fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
}

工作组件

  • 对于默认道具总是很好 - 组件可以/将在获取之前呈现 returns 响应
  • class替换为className,因为第一个是JSX
  • 中的限制词
  • ul 只能包含 li 个孩子 - 不能 div
  • 很好用 key 属性 迭代集合时

应用组件

  • 有支持意外响应的地方,你可以像error一样设置新的状态并支持它
  • 请考虑组件负责支持错误和旋转器- AppJobs

Ract 应用程序

class Jobs extends React.Component {
  render() {
    const { jobs } = this.props;
    const formattedJobs = jobs.map(job =>
      <ul key={job.id}>
        <li className="company">{job.company_name}</li>
        <li className="title">{job.title}</li>
      </ul>
    );

    return <div>{formattedJobs}</div>;
  }
}

Jobs.defaultProps = {
  jobs: []
};

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      jobs: []
    };
  }

  componentDidMount() {
    fetch("https://codepen.io/jobs.json")
      .then(response => response.json())
      .then(response => {
        if (!Array.isArray(response.jobs)) {
          throw new Error(
            `Expected response but got ${JSON.stringify(response.jobs)}`
          );
        } else {
          return response.jobs;
        }
      })
      .then(jobs => this.setState({ jobs }));
  }

  render() {
    return (
      <div className="app">
        <div className="header">
          <h1 id="header-title">Job Postings</h1>
        </div>
        <div className="content">
          <Jobs jobs={this.state.jobs} />
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));