首页 > 解决方案 > 如何在反应中获取?

问题描述

下午好,我从服务器获取json,我处理它,但是对render的调用发生了2次。谷歌,在构造函数中创建一个空对象。如果对象没有属性,则返回未定义,但我也有数组,应用程序从中崩溃。我附上代码。如何将数据取出状态?是否可以在渲染中获取并写入?

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

  componentWillMount() {
    fetch("http://localhost:3001")
      .then(response => response.json())
      .then(result => this.setState({ data: result }))
      .catch(e => console.log(e));
  }

  render() {
    const { data } = this.state;

    return <h1>{console.log(data.goals[0].gs_id)}</h1>; //падает
  }
}

标签: javascriptreactjs

解决方案


使用componentDidMount代替componentWillMount,它已被弃用。

这是克里斯托弗处理异步操作的答案中一个非常好的补充。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then(response => response.json())
      .then(result =>
        this.setState({
          data: result
        })
      )
      .catch(e => console.log(e));
  }
  render() {
    const { data } = this.state;

    return <h1> {data[0] ? data[0].title : 'Loading'} </h1>;
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


推荐阅读