【问题标题】:React - Empty Array When Rendering JSON DataReact - 渲染 JSON 数据时的空数组
【发布时间】:2017-12-11 07:05:02
【问题描述】:

为什么在渲染这个 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')
);

【问题讨论】:

    标签: javascript json reactjs fetch


    【解决方案1】:

    工作组件

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

    应用组件

    • 有地方支持意外响应,你可以设置像error这样的新状态并支持它
    • 请考虑组件负责支持错误和微调器-App 或Jobs

    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"));
    

    【讨论】:

    • 感谢您的反馈。更新以满足您提出的问题。我现在已经掌握了窍门。
    【解决方案2】:

    始终在 ComponentDidMount 中使用 fetch 语句,因为它是在您的组件第一次渲染后调用的

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

    【讨论】:

    • 会的,我避免正确处理它只是为了打印出来。但我会更新它以处理所有情况。
    【解决方案3】:

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

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

    【讨论】:

    • 知道了,谢谢。这就说得通了。我有更多关于 ajax、fetch 和 Javascript 的阅读要做,但我现在看到了。
    猜你喜欢
    • 2018-07-02
    • 1970-01-01
    • 2021-05-17
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    相关资源
    最近更新 更多